监控文件夹并查找Windows应用程序中是否有文件正在打开

3

编辑: 显然没有一种简单或方便的方法可以知道文件是否被打开/正在被进程占用。我认为这是Windows操作系统本身的问题或设计决策,因为即使像Process Explorer这样的程序也无法告诉我“mytext.txt”文件何时在其窗口旁边的记事本中打开:) 进一步的研究还表明,可靠地获取此信息的唯一方法是深入了解系统驱动程序。我的问题仍然存在,如果有人能向我展示这个驱动程序解决方案的路径,那也将不胜感激。

p.s:我真诚地认为应该有一个简单的解决方案。我的意思是,感觉整个操作系统都缺少一个功能——无法告诉一个文件是否被打开?真的吗?甚至没有API方法?对我来说,这感觉不对。

--原始问题--

我已经在网上搜索了所有答案。显然,在Windows Vista之后,添加了一个名为Restart Manager的功能,我们可以调用该dll的方法来检查文件是否被锁定。

但是,当我在一个简单的控制台应用程序中尝试此操作(受此文章启发:https://blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283和此SO答案https://dev59.com/MHRC5IYBdhLWcg3wYP6h#20623311),它可以告诉我Office文件(xls,doc等)是否被锁定/打开,但是当我在记事本中打开.txt文件或在Visual Studio中打开项目时,它无法告诉我是否被锁定。

我的程序正在监视用户系统中的预设文件夹(例如Documents文件夹),并且我想要在该文件夹中的任何文件被打开时触发事件。该程序本身不会修改文件或处理该文件,因此锁定或解锁不是问题,我只是想在监视的文件夹中的任何程序打开文件时收到通知。

现在,我正在使用此代码查找哪些进程正在锁定文件,但我觉得有一种更简单的方法可以知道何时打开文件而不是使用Win32 API。

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;
    }
}

非常感谢您的帮助。

1个回答

0
你需要知道是谁打开了一个文件,还是只需要知道它是否被锁定?
如果你只需要知道它是否被锁定,你可以使用FileSystemWatcher。这个组件将监视某个文件夹的各种变化。

我只需要知道一个文件是否被打开(锁定)。我现在会研究一下FileSystemWatcher,谢谢! - Tequilalime
不幸的是,FileSystemWatcher在访问所述目录中的文件时不会触发任何事件。所有其他NotifyFilter值都有效,但LastAccess不起作用。进一步的研究表明,由于使用了过多的系统资源,文件的LastAccessDate属性未被操作系统更新。这里也有人提出了这个问题:https://social.msdn.microsoft.com/Forums/vstudio/en-US/5752e234-6429-456c-bbd0-a2bbf49c5914/filesystemwatcherchanged-event-does-it-fire-when-a-file-is-accessed?forum=netfxbcl - Tequilalime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接