如何解决进程退出后删除时文件被使用异常
我正在使用 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)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。