码迷,mamicode.com
首页 > Windows程序 > 详细

使用c#检测文件正在被那个进程占用

时间:2015-01-13 17:27:12      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

要检测文件被那个进程占用,需要使用微软提供的工具Handle.exe,这里有微软提供的下载

我们可以在c#中调用Handle.exe 来检测到底哪个进程占用了文件

 

string fileName = @"c:\aaa.doc";//要检查被那个进程占用的文件

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

简单而有效。

使用c#检测文件正在被那个进程占用

标签:

原文地址:http://www.cnblogs.com/DoNetCShap/p/4221822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!