所以我正在创建DLL类型文件,运行它们然后我想删除它们.
但是,当我尝试删除它们时,我得到一个例外,因为它声称它们仍在被另一个进程使用.
我假设用于创建文件的代码没有正确处理资源以允许删除文件之后,这里是我创建文件的代码.
if (!Directory.Exists(PathToRobots + Generation)) { Directory.CreateDirectory(PathToRobots + Generation); } File.WriteallText(Path.Combine(PathToRobots + Generation,NameSpace + GetRobotName() + robotNumber + ".cs"),code); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters() { GenerateInMemory = false,GenerateExecutable = false,// True = EXE,False = DLL IncludeDebug@R_739_4045@ion = true,OutputAssembly = Path.Combine(FileName + ".dll") // Compilation name }; parameters.ReferencedAssemblies.Add(@"robocode.dll"); CompilerResults results = provider.CompileAssemblyFromSource(parameters,code); if (results.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { sb.AppendLine(String.Format("Error ({0}): {1}",error.ErrorNumber,error.ErrorText)); } throw new InvalidOperationException(sb.ToString()); } Assembly assembly = results.CompiledAssembly; provider.dispose();
var files = Directory.GetFiles(DirectoryPath); foreach (var file in files) { File.Delete(file); }
解决方法
请参阅
CompilerResults.CompiledAssembly Property的注释
The get accessor for the CompiledAssembly property calls the Load method to load the compiled assembly into the current application domain. After calling the get accessor,the compiled assembly cannot be deleted until the current AppDomain is unloaded.
所以当你这样做时:
Assembly assembly = results.CompiledAssembly;
您已将已编译的程序集加载到当前应用程序域中,因此已锁定该文件.为了能够删除生成的文件,您需要将其加载到单独的应用程序域中(this answer可能有助于执行此操作的具体细节).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。