Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to delete assembly (.exe)

Tags:

c#

assemblies

I've written a small app to get version numbers of files contained within a .cab file.

I extract all files from the cab to a temp directory and loop through all the files and retrieve version numbers as follows:

//Attempt to load .net assembly to retrieve information
Assembly assembly = Assembly.LoadFile(tempDir + @"\" + renameTo);
Version version = assembly.GetName().Version;
DataRow dr = dt.NewRow();
dr["Product"] = renameTo;
dr["Version"] = version.ToString();
dt.Rows.Add(dr); 

Then when finished I want to delete all the files that have been extracted as follows:

        foreach (string filePath in filePaths)
        {
            //Remove read-only attribute if set
            FileAttributes attributes = File.GetAttributes(filePath);

            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                File.SetAttributes(filePath, attributes ^ FileAttributes.ReadOnly);
            }

            File.Delete(filePath);
        }

This works for all files except except sometimes fails on .net .exe's. I can manually delete the file so it does not appear to be locked.

What should I be looking for to make this work? Is Assembly.LoadFile perhaps locking the file?

like image 984
Fishcake Avatar asked Jan 17 '23 14:01

Fishcake


2 Answers

Assembly.LoadFile does indeed lock the file. If you need to load assemblies from files and then subsequently delete the files, what you need to do is:

  1. Start a new AppDomain
  2. Load the assembly in that appdomain
  3. Only work with it there- do not use any types from the assembly in your main appdomain.
  4. Call AppDomain.Unload to tear down the AppDomain
  5. Then delete the file

You cannot delete a file containing an assembly while that assembly is loaded into an executing AppDomain.

like image 187
Chris Shain Avatar answered Jan 27 '23 21:01

Chris Shain


AssemblyName.GetAssemblyName will get the AssemblyName object without locking the file on you. see msdn. You can get the version from there.

like image 33
Mike Zboray Avatar answered Jan 27 '23 20:01

Mike Zboray