English 中文(简体)
无法删除程序集(.exe)
原标题:Unable to delete assembly (.exe)

我编写了一个小应用程序来获取.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); 

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

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

这适用于所有文件,但在.net.exe上有时会失败。我可以手动删除该文件,这样它就不会被锁定。

我应该寻找什么来实现这一目标?是集会。LoadFile可能锁定了文件?

最佳回答

程序集名称。GetAssemblyName将获取AssemblyName对象,而不会锁定您的文件。请参见msdn。您可以从那里获取版本。

问题回答

装配LoadFile确实锁定了文件。如果您需要从文件中加载程序集,然后删除文件,您需要做的是:

  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

当程序集加载到正在执行的AppDomain中时,您无法删除包含该程序集的文件。

另一种方法(除了在单独的AppDomain中使用从文件加载)是使用Assembly.Load从字节加载到主AppDomain中。

请注意,如果一个文件中有具有相同标识的程序集(即2个具有相同文件名的非强签名程序集),为了使代码完全正确,您仍然可能需要为每个程序集单独设置AppDomain。

即使使用单独的AppDomain,对于场景,使用LoadReflectionOnlyFrom从字节加载也会更安全,因为在这种情况下,卸载AppDomain失败不会导致文件锁定,您自己可以完全控制文件的锁定。对于使用从字节加载的程序集的定期加载,需要大量的读取来理解相关的问题,最好避免。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签