c# - 创建文件后删除文件

标签 c# file

所以我正在创建 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
    IncludeDebugInformation = 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 可能有助于执行此操作的细节)。

关于c# - 创建文件后删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35489376/

相关文章:

c# - 多对多保存数据时的 Entity Framework

c# - WPF 中的绑定(bind)未按预期工作

c - 丢弃来自 libcurl 的响应数据

python - python中压缩文件夹的完整文件路径

Java:为数组赋值

c# - 通用方法,是否可以返回 StreamReader 实例?

c# - 调用相同的函数直到它连接到服务器

c# - 调试与发布性能

file - 批处理文件日期时间

c++ - 从文件中读取数据到数组中