进程退出后删除时正在使用的文件异常

File being used exception when deleting after process exit

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

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)
     }
}