Search code examples
c#.net-assembly

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.


Solution

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