无法删除程序集(.exe)

Fis*_*ake 4 c# assemblies

我写了一个小应用程序来获取.cab文件中包含的文件版本号.

我将所有文件从cab提取到临时目录并循环遍历所有文件并检索版本号,如下所示:

//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); 
Run Code Online (Sandbox Code Playgroud)

然后,当我完成后,我想删除已提取的所有文件,如下所示:

        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);
        }
Run Code Online (Sandbox Code Playgroud)

这适用于所有文件,除了有时在.net .exe上失败.我可以手动删除该文件,使其看起来不会被锁定.

我应该寻找什么来使这项工作?Assembly.LoadFile可能是锁定文件吗?

Chr*_*ain 6

Assembly.LoadFile确实锁定了文件.如果需要从文件加载程序集然后删除文件,则需要执行的操作是:

  1. 启动一个新的AppDomain
  2. 在该appdomain中加载程序集
  3. 只有在那里使用它 - 不要在主appdomain中使用程序集中的任何类型.
  4. 调用AppDomain.Unload以拆除AppDomain
  5. 然后删除该文件

在将程序集加载到正在执行的AppDomain中时,无法删除包含程序集的文件.