I am trying to load a MSIL assembly using the following code :
string PathOfDll = "PathOfMsILFile (Dll)";
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom(PathOfDll);
At the end of this program I should delete this file :
File.Delete(PathOfDll);
It causes an error : 'System.UnauthorizedAccessException'
Additional information: Access to the path 'Path' is denied .
It is not relating to UAC it is just because I am loading the assembly at the start of program and when I wanna delete it manually it says that the file is in use in vshost.exe . So I say this just to show that it is for loading assemly !
So is there any way to get rid of it (something like Un-loading this assembly) ?
Note : I am writing a code to run Garbage Collector but this problem is still unsolved .
Thanks.
One possible way could be: Instead of LoadFrom
, use Load
as shown below.
Assembly asm = null;
try
{
asm = Assembly.Load(File.ReadAllBytes(path));
}
catch(Exception ex)
{
}
The accepted answer has memory leak problem. In deep, the assembly binary is loaded into memory and won't be released until your application exit.
I prefer the use of AppDomain which allows GC to clean up after using. Sample code was provided by Rene de la garza at https://stackoverflow.com/a/6259172/7864940
In brief:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With