gpt4 book ai didi

c# - 删除由 CodeDomProvider 编译创建的程序集时访问被拒绝?

转载 作者:行者123 更新时间:2023-11-30 16:29:58 25 4
gpt4 key购买 nike

如果在编译完成后在 .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
}

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

最佳答案

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

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

可能的解决方案:

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

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

关于c# - 删除由 CodeDomProvider 编译创建的程序集时访问被拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6035846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com