Search code examples
c#file-iofile-locking

Handle.exe not working when exec from code


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.

Solution

  • 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.