Dot-Net

為預設 AppDomain 設置卷影複製的正確方法是什麼

  • September 23, 2019

有關我可以使預設 AppDomain 使用某些程序集的捲影副本嗎?,它描述了在特定目錄的預設 AppDomain 中啟動卷影複製的有效解決方案。

基本上它說使用這些簡單的方法:

AppDomain.CurrentDomain.SetShadowCopyPath(aDirectory);
AppDomain.CurrentDomain.SetShadowCopyFiles();

但是因為這裡使用的方法被標記為已過時,所以我想知道現在完成相同操作的正確方法是什麼。警告消息提示:

請調查 AppDomainSetup.ShadowCopyDirectories 的使用情況

AppDomain 有一個稱為此類型的成員,SetupInformation它可能會將您帶到這個簡單的實現

AppDomain.CurrentDomain.SetupInformation.ShadowCopyDirectories = aDirectory;
AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true";

不幸的是,這沒有效果。所以問題是,有沒有辦法改變目前 appdomain 的 AppDomainSetup 來啟動卷影複製?

據我所知,這些方法僅適用於 .NET Framework 1.1 版。對於所有更高版本,您不能在主 AppDomain 上啟用卷影複製。您需要創建一個新AppDomain的並進行適當的設置。一個簡單的方法是創建一個載入器應用程序,它簡單地:

可以在應用程式碼項目的影子復製文章中找到一個很好的起點。以下程序摘自文章稍作修改(未指定記憶體路徑:

using System;
using System.IO;

namespace Loader
{
   static class Program
   {
       [LoaderOptimization(LoaderOptimization.MultiDomainHost)]
       [STAThread]
       static void Main()
       {
           /* Enable shadow copying */

           // Get the startup path. Both assemblies (Loader and
           // MyApplication) reside in the same directory:
           string startupPath = Path.GetDirectoryName(
               System.Reflection.Assembly
               .GetExecutingAssembly().Location);

           string configFile = Path.Combine(
               startupPath,
               "MyApplication.exe.config");
           string assembly = Path.Combine(
               startupPath,
               "MyApplication.exe");

           // Create the setup for the new domain:
           AppDomainSetup setup = new AppDomainSetup();
           setup.ApplicationName = "MyApplication";
           setup.ShadowCopyFiles = "true"; // note: it isn't a bool
           setup.ConfigurationFile = configFile;

           // Create the application domain. The evidence of this
           // running assembly is used for the new domain:
           AppDomain domain = AppDomain.CreateDomain(
               "MyApplication",
               AppDomain.CurrentDomain.Evidence,
               setup);

           // Start MyApplication by executing the assembly:
           domain.ExecuteAssembly(assembly);

           // After the MyApplication has finished clean up:
           AppDomain.Unload(domain);
       }
   }
}

你不得不:

  • 替換MyApplication.exe為您的可執行程序集的名稱。
  • 替換MyApplication為應用程序的名稱。
  • 替換MyApplication.exe.config為您的應用程序配置文件的名稱。如果你沒有,那麼你不需要設置它。

引用自:https://stackoverflow.com/questions/12513655