5

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.

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
Mohammad Sina Karvandi
  • 1,064
  • 3
  • 25
  • 44
  • In order to "unload" an assembly, you have to load it into a separate app domain. If you load it into your currently running app domain, you won't be able to delete the file because its in use. – Ron Beyer Jul 16 '15 at 20:11
  • 2
    See [here](http://stackoverflow.com/questions/6258160/unloading-the-assembly-loaded-with-assembly-loadfrom) for how to unload an AppDomain, which will "unload" all assemblies it uses.. – D Stanley Jul 16 '15 at 20:11
  • @DStanley actually I try your suggested link before but it causes many new errors. please see my accepted answer it works and It is what I exactly try to do but anyway thank you – Mohammad Sina Karvandi Jul 16 '15 at 20:30

2 Answers2

5

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

}
Vinkal
  • 2,964
  • 1
  • 19
  • 19
1

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);
hlv_trinh
  • 11
  • 3