首页 >后端开发 >C++ >如何使用重新启动管理器 API 识别在 .NET 中锁定文件的进程?

如何使用重新启动管理器 API 识别在 .NET 中锁定文件的进程?

Linda Hamilton
Linda Hamilton原创
2025-01-19 22:26:10809浏览

How to Identify Processes Locking a File in .NET Using the Restart Manager API?

利用 .NET Framework 识别锁定文件的进程

传统上,查明 .NET 框架内持有文件锁的特定进程是一项重大挑战。 然而,随着现代 Windows 的进步,重新启动管理器 API 现在提供了一种可靠的机制来跟踪此信息。

解决方案实施:

以下代码片段提供了一种可靠的方法来识别已在指定文件上建立锁定的进程:

<code class="language-csharp">public static List<Process> IdentifyFileLockers(string filePath)
{
    uint sessionHandle;
    string sessionKey = Guid.NewGuid().ToString();
    List<Process> lockedByProcesses = new List<Process>();

    int result = RmStartSession(out sessionHandle, 0, sessionKey);
    if (result != 0) throw new Exception("Failed to initiate restart session.  Unable to identify file locker.");

    try
    {
        const int ERROR_MORE_DATA = 234;
        uint processesNeeded = 0,
            processesReturned = 0,
            rebootReasons = RmRebootReasonNone;

        string[] resources = new string[] { filePath }; // Targeting a single resource.

        result = RmRegisterResources(sessionHandle, (uint)resources.Length, resources, 0, null, 0, null);

        if (result != 0) throw new Exception("Resource registration failed.");

        //Note: A race condition exists here. The initial RmGetList() call returns
        //      the total process count.  Subsequent RmGetList() calls to retrieve
        //      actual processes might encounter an increased count.
        result = RmGetList(sessionHandle, out processesNeeded, ref processesReturned, null, ref rebootReasons);

        if (result == ERROR_MORE_DATA)
        {
            // Allocate an array to store process information.
            RM_PROCESS_INFO[] processInfoArray = new RM_PROCESS_INFO[processesNeeded];
            processesReturned = processesNeeded;

            // Retrieve the process list.
            result = RmGetList(sessionHandle, out processesNeeded, ref processesReturned, processInfoArray, ref rebootReasons);
            if (result == 0)
            {
                lockedByProcesses = new List<Process>((int)processesReturned);

                // Iterate through results and populate the return list.
                for (int i = 0; i < processesReturned; i++)
                {
                    try
                    {
                        //Attempt to get the process by ID.  May fail if the process is already gone.
                        Process p = Process.GetProcessById(processInfoArray[i].Process.dwProcessId);
                        lockedByProcesses.Add(p);
                    }
                    catch (ArgumentException) { } // Ignore processes that no longer exist.
                }
            }
        }
    }
    finally
    {
        RmEndSession(sessionHandle);
    }

    return lockedByProcesses;
}</code>

重要提示:执行此代码需要非特权的注册表访问。如果进程缺乏必要的权限,建议实现 IPC 机制(例如命名管道)以将调用委托给特权进程。

以上是如何使用重新启动管理器 API 识别在 .NET 中锁定文件的进程?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn