3

如果在编译完成后在 .NET 中使用 CodeDomProvider 类,则无法删除输出程序集。我希望能够删除输出程序集。File.Delete 返回拒绝访问异常。

string asmPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".exe");
string keyPath = "some path to a *.snk file that works";
// build compiler
CodeDomProvider dom = CodeDomProvider.CreateProvider("VisualBasic");
CompilerParameters cp = new CompilerParameters();
cp.TreatWarningsAsErrors = false;
cp.GenerateInMemory = false;
cp.GenerateExecutable = true;
cp.CompilerOptions = "/target:winexe /keyfile:\"" + keyPath + "\"";
cp.OutputAssembly = asmPath;
// add all the other assembly references
string netPath = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\";
cp.ReferencedAssemblies.Add(netPath + @"System.dll");
cp.ReferencedAssemblies.Add(netPath + @"System.Core.dll");
cp.ReferencedAssemblies.Add(netPath + @"System.Data.dll");
cp.ReferencedAssemblies.Add(netPath + @"System.Xml.dll");
CompilerResults cr = dom.CompileAssemblyFromSource(cp, new string[] { code });
if (cr.Errors.Count == 0)
{
    cr.TempFiles.Delete();
    dom.Dispose();
// do stuff
...
//
    File.Delete(asmPath); // fails here Access Denied
}

编辑作为一种解决方法,我在类上使用静态构造函数来搜索临时文件夹并删除以前创建的程序集。

4

1 回答 1

3

我怀疑问题是程序集已加载(在内存中),并打开了输出文件,就像当前加载的任何其他程序集都有其可执行文件的句柄一样。

dom 实例或实例也有可能(尽管我认为不太可能)CompilerResults对打开的文件有引用。也不是IDisposable,所以我怀疑他们没有打开文件。

可能的解决方案:

您可以将程序集编译到内存中。也就是说,不输出文件。这解决了眼前的问题。但是,您仍然遇到编译后的程序集保留在内存中的问题。如果不拆除应用程序域,就无法卸载程序集。

您可以创建一个单独的应用程序域来进行编译,然后将结果传回您的主应用程序域。然后,您可以关闭编译器应用程序域,这将从内存中删除已编译的程序集,并释放引用您刚刚创建的文件的所有文件句柄。然后您的主程序可以删除有问题的文件。

于 2011-05-17T22:56:32.760 回答