进程退出后删除时文件被使用异常

问题描述

我正在使用 ImageMagick( https://imagemagick.org) 转换命令,它将图像从一种格式转换为另一种格式。我有 CommandExecutor 类,

public static class CommandExecutor
{
    public static bool Execute(string cmd)
    {
        var batchFilePath = Path.Combine(AppSettings.BasetoolsPath,$"{Guid.NewGuid().ToString()}.bat");
        try
        {
            File.WriteallText(batchFilePath,cmd);
            var process = new Process();
            var startInfo = new processstartinfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.FileName = batchFilePath;
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit(10000);
            return true;
        }
        finally
        {
            if (File.Exists(batchFilePath))
            {
                File.Delete(batchFilePath);
            }
        }
    } 
}

我正在动态创建输入图像,然后 convert.exe 将创建一个输出图像。

File.WriteallBytes(inputimagePath,image);
CommandExecutor.Execute(command);
if (File.Exists(inputimagePath))
{
    File.Delete(inputimagePath);
}
if (File.Exists(outputimagePath))
{
    File.Delete(outputimagePath);
}

在我的作品中,我看到使用异常的文件过多。使用后如何清理文件

解决方法

你可以依靠IOException

while (File.Exists(path))
{
     try
     {
        File.Delete(path);
     }
     catch (IOException ex)
     {
     }
}

或者,如果bat文件是可管理的,批处理文件可以自行删除(勾选here)。所以 File.Exists 会仔细检查。

或者,您可以使用流程'Exited 事件,

var process = Process.Start(processInfo);
process.EnableRaisingEvents = true;
process.Exited += Process_Exited;

private void Process_Exited(object sender,EventArgs e)
{
     if (File.Exists(path)) { // if still exists
         File.Delete(path)
     }
}