0

I am using ImageMagick( https://imagemagick.org) convert command which converts an image from one format to another. I have 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);
            }
        }
    } 
}

I am dynamically creating input image and then convert.exe will create a output image.

File.WriteAllBytes(inputImagePath, image);
CommandExecutor.Execute(command);
if (File.Exists(inputImagePath))
{
    File.Delete(inputImagePath);
}
if (File.Exists(outputImagePath))
{
    File.Delete(outputImagePath);
}

In my production I am seeing too much file in use exception. How to clean the file after use?

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

1 Answers1

1

You can rely on IOException,

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

Or, If bat file is manageable, batch file can delete itself (check here). So File.Exists will double check.

Or, you can use process' Exited event,

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)
     }
}
Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37