Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an assembly after loading

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.

like image 950
Mohammad Sina Karvandi Avatar asked Jul 16 '15 20:07

Mohammad Sina Karvandi


2 Answers

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)
{

}
like image 137
Vinkal Avatar answered Sep 24 '22 08:09

Vinkal


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);
like image 1
hlv_trinh Avatar answered Sep 20 '22 08:09

hlv_trinh