Removing an assembly after downloading
I am trying to load an MSIL assembly using the following code:
string PathOfDll = "PathOfMsILFile (Dll)";
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom(PathOfDll);
At the end of this program, I have to delete this file:
File.Delete(PathOfDll);
This throws an error: "System.UnauthorizedAccessException"
Additional information: Access to the path 'Path' is denied .
This is not the case for UAC because I load the assembly at the beginning of the program and when I want to manually delete it, it says the file is in use in vshost.exe. So I'm just saying this to show that this is for assembly boot!
So, is there a way to get rid of it (something like Un-loading this assembly)?
Note. I am writing code to run the garbage collector, but this issue is still not resolved.
Thank.
source to share
There is a memory leak issue in the accepted answer. In depth, the assembly binary is loaded into memory and will not be released until the application exits.
I prefer to use AppDomain which allows GC to be cleaned up after use. Sample code was provided by Rene de la garza at fooobar.com/questions/150273 / ...
In short:
AppDomain dom = AppDomain.CreateDomain("some");
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = pathToAssembly;
Assembly assembly = dom.Load(assemblyName);
//Do something with the loaded 'assembly'
AppDomain.Unload(dom);
source to share