2012-09-17 40 views
2

我正在C#中創建一個卸載實用程序。該實用程序將取消註冊通過Regasm註冊的文件,然後它將刪除這些文件。無法刪除通過C#中的Assembly.LoadFrom加載的文件。

Assembly asm = Assembly.LoadFrom("c:\\Test.dll") 
int count = files.Length; 
RegistrationServices regAsm = new RegistrationServices(); 
if (regAsm.UnregisterAssembly(asm)) 
MessageBox.Show("Unregistered Successfully"); 

上述代碼工作正常,但是當我嘗試刪除Test.dll時,出現錯誤並且無法刪除它。 我知道Assembly.LoadFrom(「c:\ Test.dll」)已經保存了對這個文件的引用,並且不會丟失它。有什麼辦法可以解決這個問題嗎?

感謝和問候

+0

什麼是出現的錯誤。 – gideon

+0

您無法卸載程序集,但可以卸載應用程序域。 –

回答

3

您需要在另一個應用程序域中加載該類型。通常這是通過將從MarshalByRefObject派生的類型加載到另一個域中,將實例編組到原始域並通過代理執行該方法來完成的。這聽起來很難,那麼這是這樣的檢驗:

public class Helper : MarshalByRefObject // must inherit MBRO, so it can be "remoted" 
{ 
    public void RegisterAssembly() 
    { 
     // load your assembly here and do what you need to do 
     var asm = Assembly.LoadFrom("c:\\test.dll", null); 
     // do whatever... 
    } 
} 

static class Program 
{ 
    static void Main() 
    { 
     // setup and create a new appdomain with shadowcopying 
     AppDomainSetup setup = new AppDomainSetup(); 
     setup.ShadowCopyFiles = "true"; 
     var domain = AppDomain.CreateDomain("loader", null, setup); 

     // instantiate a helper object derived from MarshalByRefObject in other domain 
     var handle = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().Location, typeof (Helper).FullName); 

     // unwrap it - this creates a proxy to Helper instance in another domain 
     var h = (Helper)handle.Unwrap(); 
     // and run your method 
     h.RegisterAssembly(); 
     AppDomain.Unload(domain); // strictly speaking, this is not required, but... 
     ... 
    } 
} 
1

您不能卸載任何加載的程序集。 Shadow copying,或將裝配加載到另一個域是什麼將幫助你。

+0

謝謝你們,問題成功解決。 – user288645