使用微软提供的handle.exe来进行检测文件被占用, 这里是要覆盖一个文件,所以覆盖前先检测这个文件有无进程占用,有的话就kill进程,然后删掉文件
这个检测进程时间耗时比较长,测了下,有进程占用的话检测出来大概10s以上,所以不能每个文件都直接检测,先执行文件删除,有异常只能是文件被占用,再去执行解除占用;
handle.exe的下载地址:https://docs.microsoft.com/zh-cn/sysinternals/downloads/handle
public void KillProcess(string fileName)
{
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
catch (Exception ex)
{
Logger.LogException(ex);
Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
// kill是异步操作,需要使用WaitForExit来确保进程已经完全退出
Process.GetProcessById(int.Parse(match.Value)).WaitForExit();
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.WriteLine(string.Format("{0}文件被占用处理完毕", fileName));
}
}
平时自己使用的话,可以用process-explorer来看进程情况,是个GUI界面,下载地址:https://docs.microsoft.com/zh-cn/sysinternals/downloads/process-explorer