How do I find out which process is locking a file using .NET?

前端 未结 6 974
渐次进展
渐次进展 2020-11-22 00:42

I\'ve seen several of answers about using Handle or Process Monitor, but I would like to be able to find out in my own code (C#) which process is locking a file.

I ha

6条回答
  •  死守一世寂寞
    2020-11-22 00:58

    It is very complex to invoke Win32 from C#.

    You should use the tool Handle.exe.

    After that your C# code have to be the following:

    string fileName = @"c:\aaa.doc";//Path to locked file
    
    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();
    }
    

提交回复
热议问题