【问题标题】:File being used exception when deleting after process exit进程退出后删除时文件被使用异常
【发布时间】:2021-03-01 16:42:17
【问题描述】:

我正在使用 ImageMagick(https://imagemagick.org) convert 命令将图像从一种格式转换为另一种格式。我有 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);
}

在我的制作中,我看到太多文件正在使用异常。使用后如何清理文件?

【问题讨论】:

  • WaitForExit 超时。您是否检查过是否仍有子进程在运行?
  • 它从未在 dev 上重现。仅在生产中

标签: c# file process imagemagick


【解决方案1】:

你可以依赖IOException

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

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

或者,可以使用process'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)
     }
}

【讨论】:

  • 不幸的是,我必须在使用后删除该文件。让我试试退出事件
猜你喜欢
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
相关资源
最近更新 更多