Question

I am trying to use handle.exe to discover which process owns a file. When I run handle on it's own through the commandline it works as expected. However, when I exec it from within my code I always get back that no process is locking the file.

My code to run Handle.exe:

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = theFileName;
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 (System.Text.RegularExpressions.Match match in 
         System.Text.RegularExpressions.Regex.Matches(outputTool, matchPattern)) {
    Process p = Process.GetProcessById(int.Parse(match.Value));
    Console.WriteLine("Holding Process: " + p.Id);
}

I've also tried some of the other ways to find file ownership suggest in this SO question: Using C#, how does one figure out what process locked a file? All still reporting that nothing has control of the file.

To test this stuff I have a separate test program basically just running this:

    using (FileStream theStream = new FileStream(theFileName, FileMode.Open, FileAccess.Read, FileShare.None)) {
        while (true) ;
    }

Edit: I run Visual Studio as an administrator so any process I start through code gets the same privileges. Of course this is only while debugging, but I need to a least get it working in one environment before worrying about others.

After handle is run outputTool is

Handle v3.5
Copyright (C) 1997-2012 Mark Russinovich
Sysinternals - www.sysinternals.com

No matching handles found.
Was it helpful?

Solution 2

I've figured it out. My file path had an extra '\'. Apparently this confuses handle, but not File.Open(...).

theFileName = "C:\ProgramData\MyApp\\imagefile.tiff"

Whenever I tried running handle.exe in the Windows cmd I didn't include the extra '\'.

I guess since I never included the file path in my question, it was impossible for anyone else to figure it out. Sorry SO users.

OTHER TIPS

Handle.exe must be run elevated in order to function. I suspect that if you dump the contents of outputTool, you'll find that it says "Initialization error: Make sure that you are an administrator."

Running your own app elevated should automatically launch handle.exe elevated as well, which will resolve the problem. Unfortunately, you can not simply modify your app to launch handle.exe elevated. That would require using tool.StartInfo.Verb = "runas";, which requires tool.StartInfo.UseShellExecute = true;, which would conflict with tool.StartInfo.RedirectStandardOutput = true;

You can add an application manifest with requestedExecutionLevel set to requireAdministrator to ensure that your app is always launched elevated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top