Original: C#.net how to dynamically load and unload an assembly (. dll or. exe) 6-----Replace the assembly file without uninstalling the program domain.
When an assembly file is loaded into the AppDomain, the file cannot be replaced and deleted before appdomain.unload.
The image copy feature of AppDomainSetup enables you to replace or delete assembly files without uninstalling the program.
AppDomain domain = Appdomain.createdomain ("a");
Domain. ExecuteAssembly (@ "Loads\test.exe");
File.delete (@ "Loads\test.exe");
The above code does not call AppDomain.Unload (domain) before deleting the file; , an "Access Denied" exception appears.
Next we turn on the image Copy feature and you will find that the target assembly file is deleted correctly.
AppDomain domain = Appdomain.createdomain ("a");
Open image copy.
Domain. Setshadowcopyfiles ();
Sets the path of the assembly to be set for the image.
Domain. Setshadowcopypath (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "loads"));
Domain. ExecuteAssembly (@ "Loads\test.exe");
File.delete (@ "Loads\test.exe");
We use "assembly.getexecutingassembly ()" in "Loads\test.exe". Location "View, you will find that the assembly file is copied to" C:\Documents and Settings\user1\local Settings\Application Data\assembly\dl2\ 6e9nkvqy.yol\dhp83obd.j9j\9730b8d1\00fb5179_6d04c601\test.exe "In such a directory, this is also the root cause (^_^) that the assembly is deleted correctly. Because the location of the target assembly has changed, we have to make further settings, otherwise the target assembly has an error loading the dynamic reference or reading the configuration file.
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, this time is no problem.
C#.net how to dynamically load and unload an assembly (. dll or. exe) 6-----Replace the assembly file without uninstalling the program domain.