c# - 日志进程 ID、机器名称和文件的所有者,该文件由 Windows 服务器上的另一个进程使用 c# 使用

标签 c# .net iis windows-server

在我的应用程序中,我在远程位置有一些文件,比如 \\server\sharedfolder,程序根据用户操作执行移动或删除等操作,并将相应的文件移动到另一个用户或文件夹。但是如果某个用户打开文件夹或文件,操作显然会失败。

我的目标是记录当前持有文件的用户,包括进程、机器名和用户名。

尝试过的解决方案:

How do I determine the owner of a process in C#?

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

也尝试使用上述解决方案进行模拟,但没有成功。

在服务器上,我在 computer management-> system tools-> opened files 中查看了所有用户的日志和其他详细信息。

我的解决方案是完全使用 C# 编程的。

P.S 由于政策原因不能分享任何代码或片段。

更新:

对于寻找类似方法或解决方案的任何人,接受答案以及 this one here和具有管理员权限的模拟相结合,将产生最终输出。

最佳答案

这里有另一个答案:stackoverflow.com/questions/317071/...

我为此尝试了多种解决方案,但唯一得到正确答案的是 Eric J.。已回应。我测试了这个,它适用于正常大小的文件,而且对于被 Windows 服务(如 MSSQL 服务)锁定的进程,我没有得到任何正确的答案。这是由 win32 api 完成的。

我只是重申Eric J.的答案:

using System.Runtime.InteropServices;
using System.Diagnostics;
static public class FileUtil
{
[StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);
        if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

关于c# - 日志进程 ID、机器名称和文件的所有者,该文件由 Windows 服务器上的另一个进程使用 c# 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787382/

相关文章:

asp.net - 在 Azure WebRoles 中启用 HTTP 严格传输安全 (HSTS)

asp.net - 我可以在 IIS 上部署 Azure 项目吗?

javascript - mvc 5如果dropdownlist选择的选项比所需的其他模型属性更多

c# - AppDomain 是否等同于 .NET 代码的进程?

c# - Marshal.AllocHGlobal VS Marshal.AllocCoTaskMem,Marshal.SizeOf VS sizeof()

.net - 使用 Task.Wait() 代码包装 Async/Await IAsyncOperations 有哪些风险?

php - 当应用程序池使用 'ApplicationPoolIdentity' 时,IIS 8.5 使用什么用户帐户?

c# - 实体类必须定义在哪一层?

c# - 将文本转换为图像?

c# - 为什么我可以在这段代码中放置和放大?