Search code examples
c#dll.net-assembly

How to unloaded a loaded Assembly


I'm trying to load an assembly, use Reflection to get all the class' inside that .dll, and then delete the .dll. However I am getting access denied exception when trying to delete the .dll. This is not due to access rights as I can delete the .dll if I do not load it first.

I've looked on MSDN, and apparently there is no way to "unload", but I'm hoping that there might be another way.

Assembly assembly;
assembly = Assembly.LoadFrom(filepath);

Type[] listOfAllClassInDll = assembly.GetTypes();
List<string> listOfAllClassNamesInDll = new List<string>();

        foreach (Type classInDll in listOfAllClassInDll)
        {
           listOfAllClassNamesInDll.Add(classInDll.Name);
        }

File.Delete(filepath);

Solution

  • Actually you can't do it straightforward.. There is why: http://blogs.msdn.com/b/jasonz/archive/2004/05/31/145105.aspx

    But you can dynamically load your assembly in another AppDomain. Then when you don't need your assembly - you have to unload you AppDomain with loaded assembly.

    Example there: https://bookie.io/bmark/readable/9503538d6bab80