C#.Net 如何動態載入與卸載程式集(.dll或者.exe)6-----在不卸載程式域的前提下替換組件檔。

來源:互聯網
上載者:User

標籤:dom   director   let   卸載   ado   https   dir   引用   .dll   

原文:C#.Net 如何動態載入與卸載程式集(.dll或者.exe)6-----在不卸載程式域的前提下替換組件檔。

當某個組件檔被載入AppDomain,該檔案在AppDomain.Unload之前是不能被替換和刪除的。
使用AppDomainSetup的影像複製功能可以實現在不卸載程式的情況下替換或者刪除組件檔。

AppDomain domain = AppDomain.CreateDomain("a");
domain.ExecuteAssembly(@"loads\test.exe");
File.Delete(@"loads\test.exe");


上述代碼沒有在刪除檔案前調用 AppDomain.Unload(domain); ,所以會出現"拒絕訪問"的異常。
接下來我們開啟影像複製功能,你會發現目標組件檔被正確刪除。

AppDomain domain = AppDomain.CreateDomain("a");

// 開啟影像複製。
domain.SetShadowCopyFiles();
// 設定要進行影像設定的程式集路經。
domain.SetShadowCopyPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loads"));

domain.ExecuteAssembly(@"loads\test.exe");
File.Delete(@"loads\test.exe");


我們在"loads\test.exe"中使用"Assembly.GetExecutingAssembly().Location"查看,你會發現組件檔被複製到"c:\documents and settings\user1\local settings\application data\assembly\dl2\6e9nkvqy.yol\dhp83obd.j9j\9730b8d1\00fb5179_6d04c601\test.exe"這樣一個目錄中,這也是程式集被正確刪除的根本原因(^_^)。正因為目標程式集的位置發生變化,因此我們要做更進一步的設定,否則目標程式集在載入動態引用或者讀取設定檔時出錯。

AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loads");
setup.ConfigurationFile = Path.Combine(setup.ApplicationBase, "test.exe.config");
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;

AppDomain domain = AppDomain.CreateDomain("a", null, setup);
domain.ExecuteAssembly(@"loads\test.exe");

File.Delete(@"loads\test.exe");


ok, 這回沒問題了。

C#.Net 如何動態載入與卸載程式集(.dll或者.exe)6-----在不卸載程式域的前提下替換組件檔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.