【问题标题】:Closing Open Files using C#使用 C# 关闭打开的文件
【发布时间】:2010-12-18 03:27:41
【问题描述】:

我有一种情况,人们连接到共享上的文件,它阻止我覆盖文件。我正在尝试编写一个方法来查看我提供的文件路径当前是否以这种方式锁定并关闭此资源的网络会话。

我查看了 ADSI Winnt 提供程序,但未实现 Resources.Remove 成员。然后我查看了 Win32_ServerSession,虽然我可以使用 Delete 成员,但它会杀死给定用户的所有资源。我需要弄清楚如何更具体。

我一直在使用 GetRelationsShips 和 Properties,但现在我很困惑。

【问题讨论】:

  • 我不知道你是否能做到这一点——如果你能做到,这是否明智?替代方案 - 你能以某种方式向用户发送消息吗 - 电子邮件、通过应用程序等?
  • 嗨,克里斯。在我看来,在网络上的读/写资源文件之上自动部署总是错误的。我唯一会这样做的情况是,如果文件本身在设计上都是只读的 - 但是作为设置开发人员,我们总是面临“只是做”的心态。我使用 C# 和 FileSystemWatcher 实现了一个检查器,用于写入网络共享中的文件。它从未奏效,因为引发的事件因底层硬件而异。以下是一些细节:codeproject.com/KB/files/…
  • 其实这个问题与部署/设置没有任何关系。在这种情况下,自动构建试图归档到已知文件夹,并且有锁定的文件挡住了路。

标签: c# wmi


【解决方案1】:

很难考虑这样做的所有后果,因为您不一定能预测当前锁定文件的应用程序的结果行为。

还有其他方法可以做到这一点吗?例如,您是否必须立即覆盖文件,或者您是否可以让某个外部进程每隔几分钟不断尝试覆盖文件,直到成功?

【讨论】:

  • 我会给你“不要那样做”的答案。 :-) 我知道我没有说明为什么我需要这样做,但它们是真实的。幸运的是,我将任务交给了其他人。 :-)
【解决方案2】:

我遇到了同样的问题。 到目前为止,我知道,唯一的方法是使用 Win32API:

[DllImport("Netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern int NetFileClose(string servername, int id);

我做了一个简短的尝试来实现这一点,我可以正确枚举文件, 但是在我的代码中-我只是查看了一下-关闭文件的代码 设置为评论。如果您愿意尝试一下,我可以发送一个库 [围绕 NetFileXXX 的包装器] 和一个简短的演示,但是,正如我所说:我从未关闭过文件。但这可能是一条捷径。

我不知道,现在如何在 * 上交换文件 :-( ?!?

br--马布拉

【讨论】:

    【解决方案3】:

    您可以使用提供完整文件路径的代码,它会返回一个List<Processes> 锁定该文件的任何内容:

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

    然后,迭代进程列表并关闭它们:

        string[] files = Directory.GetFiles(target_dir);
        List<Process> lstProcs = new List<Process>();
    
        foreach (string file in files)
        {
            lstProcs = ProcessHandler.WhoIsLocking(file);
            if (lstProcs.Count > 0) // deal with the file lock
            {
                foreach (Process p in lstProcs)
                {
                    if (p.MachineName == ".")
                        ProcessHandler.localProcessKill(p.ProcessName);
                    else
                        ProcessHandler.remoteProcessKill(p.MachineName, txtUserName.Text, txtPassword.Password, p.ProcessName);
                }
            }
        }
    

    并且取决于文件是否在本地计算机上:

    public static void localProcessKill(string processName)
    {
        foreach (Process p in Process.GetProcessesByName(processName))
        {
            p.Kill();
        }
    }
    

    或网络计算机:

    public static void remoteProcessKill(string computerName, string fullUserName, string pword, string processName)
    {
        var connectoptions = new ConnectionOptions();
        connectoptions.Username = fullUserName;  // @"YourDomainName\UserName";
        connectoptions.Password = pword;
    
        ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);
    
        // WMI query
        var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
    
        using (var searcher = new ManagementObjectSearcher(scope, query))
        {
            foreach (ManagementObject process in searcher.Get()) 
            {
                process.InvokeMethod("Terminate", null);
                process.Dispose();
            }
        }
    }
    

    参考资料:
    How do I find out which process is locking a file using .NET?

    Delete a directory where someone has opened a file

    【讨论】:

      最近更新 更多