How to force to delete access denied file in c#

739 views Asked by At

In a web application at run-time, i load an external assembly (*.dll file) and run some part of it's code and then i want to unload and delete the file!

this is my load code:

var assembly = Assembly.Load(AssemblyName.GetAssemblyName(@"..\..\anexternallibrary.dll"));

How can i unload it and release the file? the deleting file also could not be done an throws file access denied exception.

How to force to delete it without killing the related process?

1

There are 1 answers

0
Lloyd On

Once you load the assembly into the AppDomain you cannot unload it you have to unload the whole AppDomain instead.

You can create new AppDomain, however they can't directly talk to each other without marshalling between the two.

In terms of files though, you may be able to use Assembly.Load(byte[]), for example:

byte[] assembly_bytes;

using (var file = new FileStream(
    @"..\..\anexternallibrary.dll",
    FileMode.Open,
    FileAccess.Read,
    FileShare.None))
{
    assembly_bytes = new byte[file.Length];
    file.Read(assembly_bytes,0,assembly_bytes.Length);
}

Assembly assembly = Assembly.Load(assembly_bytes);

You'd then be free to delete the source file. However the issue with unloading still applies.