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.

+3


source to share


2 answers


One possible way could be: Instead, LoadFrom

use Load

as shown below.



Assembly asm = null;
try
{
    asm = Assembly.Load(File.ReadAllBytes(path));
}
catch(Exception ex)
{

}

      

+4


source


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

      

+1


source







All Articles