动态加载.dll文件后释放.dll和.pdb

Release .dll and .pdb after loading .dll file dynamically

我正在构建一个 windows 应用程序,我可以在其中通过单击按钮调用编码 UI 项目 (名为 RecordAndPlayback 的项目)。我的目标是调用编码 UI 项目中的测试方法,然后能够修改测试,然后从我的 win 应用程序中调用它,而无需使用相同的按钮关闭它。

我成功地调用了测试方法,但是之后修改测试方法时遇到了问题。每当我构建编码 UI 项目时,我都会收到错误

ERROR CSC(0,0): Unexpected error creating debug information file '...\obj\Debug\RecordAndPlayback.PDB' -- '...\obj\Debug\RecordAndPlayback.pdb: The process cannot access the file because it is being used by another process.

我用AppDomain加载了里面的dll,然后卸载了AppDomain,希望dll被释放。我设法做到了,但后来我在 .pdb 文件中遇到了上述错误。我找到了另一个更简单的解决方案,但仍然遇到上述问题。

到目前为止,这是我的代码示例:

string dllPath = @"...\bin\Debug\RecordAndPlayback.dll";
byte[] fileContent;
using (FileStream dll = File.OpenRead(dllPath))
{
    fileContent = new byte[dll.Length];
    dll.Read(fileContent, 0, (int)dll.Length);
}
var DLL = Assembly.Load(fileContent);

Playback.Initialize();

foreach (Type type in DLL.GetExportedTypes())
{
    if (type.Name == "CodedUITest1")
    {
        var c = Activator.CreateInstance(type);
        try
        {
            type.InvokeMember("CodedUITestMethod1", BindingFlags.InvokeMethod, null, c, new object[] { });
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        break;
    }
}
Playback.Cleanup();

我尝试使用 AppDomain,但没有成功。实际上,上面的代码是我迄今为止得到的最好的代码,我确信 .dll 文件已发布,因为我可以删除它。此外,bin 文件夹中的 .pdb 文件已发布(也能够将其删除)。我的问题是 obj 文件夹中的 .pdb 文件。唯一的方法是我必须关闭我的 windows 应用程序项目,这样我才能构建我的编码 UI 项目。

如何在不关闭我的 win 应用程序的情况下解决这个问题?

我找到了解决问题的方法。试了很多网上的解决办法,都是一样的问题。 .dll 文件正在被另一个进程使用,或者 .pdb 文件正在被另一个进程使用。

我上面的代码,正如我所提到的,除了 .pdb 文件外都是有效的,老实说我没有找到解决方案。所以,我解决了它。我修改了构建选项,所以我根本不生成 .pdb 文件。

为了禁用 pdb 文件生成,您需要在单击“构建”选项卡下部的 "Advanced..." 按钮后使用项目属性中可用的 "Advanced build settings" 对话框。

为发布构建配置设置 Output - Debug info: to None,将不会生成任何 pdb 文件。

解决了我的问题。虽然它并没有真正修复它,但我删除了导致问题的文件。希望这对其他人有帮助