【发布时间】:2011-08-27 12:13:42
【问题描述】:
如果在编译完成后在 .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
}
编辑作为一种解决方法,我在类上使用静态构造函数来搜索临时文件夹并删除以前创建的程序集。
【问题讨论】:
-
我没有任何问题。
-
禁用您的病毒扫描程序。他们对不知从何而来的 DLL 感到方式太兴奋了。任意循环睡眠一段时间是不完美的解决方法。
标签: c# file-io access-denied delete-file dynamic-compilation