Using C#, how does one figure out what process locked a file?

前端 未结 9 2107
死守一世寂寞
死守一世寂寞 2020-11-22 13:03

In Windows, how do I determine (using C#) what process locked a file?

Third-party tools are helpful, but not what I\'m looking for.

9条回答
  •  忘掉有多难
    2020-11-22 13:27

    I rewrote the GetProcessesLockingFile() method in the solution. The code was not working.

    For example, you have a folder "C:\folder1\folder2" and a process in folder2 (process1). If the process was running, GetProcessesLockingFile() was returning "C:\folder1\folder2". So the condition if (files.Contains(filePath)) => if ("C:\folder1\folder2".contains("C:\folder1\folder2\process1")) was never true.

    So this is my solution:

    public static List GetProcessesLockingFile(FileInfo file)
    {
        var procs = new List();
    
        var processListSnapshot = Process.GetProcesses();
        foreach (var process in processListSnapshot)
        {
            if (process.Id <= 4) { continue; } // system processes
    
            List paths = GetFilesLockedBy(process);
            foreach (string path in paths)
            {
                string pathDirectory = path;
                if (!pathDirectory.EndsWith(Constants.DOUBLE_BACKSLASH))
                {
                    pathDirectory = pathDirectory + Constants.DOUBLE_BACKSLASH;
                }
                string lastFolderName = Path.GetFileName(Path.GetDirectoryName(pathDirectory));
    
                if (file.FullName.Contains(lastFolderName))
                {
                    procs.Add(process);
                }
            }
        }
        return procs;
    }
    

    Or with a string parameter:

    public static List GetProcessesLockingFile(string filePath)
    {
        var procs = new List();
    
        var processListSnapshot = Process.GetProcesses();
        foreach (var process in processListSnapshot)
        {
            if (process.Id <= 4) { continue; } // system processes
    
            List paths = GetFilesLockedBy(process);
            foreach (string path in paths)
            {
                string pathDirectory = path;
                if (!pathDirectory.EndsWith(Constants.DOUBLE_BACKSLASH))
                {
                    pathDirectory = pathDirectory + Constants.DOUBLE_BACKSLASH;
                }
                string lastFolderName = Path.GetFileName(Path.GetDirectoryName(pathDirectory));
    
                if (filePath.Contains(lastFolderName))
                {
                    procs.Add(process);
                }
            }
        }
        return procs;
    }
    

提交回复
热议问题