C# 如何删除被C中的另一个进程锁定的文件?

C# 如何删除被C中的另一个进程锁定的文件?,c#,file-locking,C#,File Locking,我正在寻找一种方法来删除被另一个进程使用C锁定的文件。我怀疑该方法必须能够找到哪个进程正在锁定该文件,可能是通过跟踪句柄,虽然我不知道如何在C中执行此操作,但请先关闭该进程,然后才能使用file.delete完成文件删除。您可以使用此程序查找哪个进程锁定了您的文件。它是一个命令行工具,所以我猜您使用它的输出。我不确定是否可以通过编程方式找到它 如果删除文件可以等待,则可以在下次启动计算机时将其指定为删除: 启动REGEDT32 W2K或REGEDIT WXP并导航到: HKEY_LOCAL_MA

我正在寻找一种方法来删除被另一个进程使用C锁定的文件。我怀疑该方法必须能够找到哪个进程正在锁定该文件,可能是通过跟踪句柄,虽然我不知道如何在C中执行此操作,但请先关闭该进程,然后才能使用file.delete完成文件删除。

您可以使用此程序查找哪个进程锁定了您的文件。它是一个命令行工具,所以我猜您使用它的输出。我不确定是否可以通过编程方式找到它

如果删除文件可以等待,则可以在下次启动计算机时将其指定为删除:

启动REGEDT32 W2K或REGEDIT WXP并导航到:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
W2K和WXP

W2K:EditAdd值…数据类型:REG_MULTI_sz值名称:PendingFileRenameOperationsOK

WXP:EditNewMulti-String值输入 挂起文件重命名操作

在数据区域中,输入要删除的\??\+文件名。LFNs可能 可以在不嵌入引号的情况下输入。要删除C:\Long Directory Name\Long File Name.exe,请输入以下数据:

\??\C:\Long Directory Name\Long File Name.exe
然后按OK

目标文件名为空零字符串。它被输入 详情如下:

W2K:EditBinaryselect数据格式:hex单击十六进制字符串末尾的Enter 0000 four zerosOK

WXP:右键单击值选择修改二进制数据在十六进制字符串末尾单击ENTER 0000 four zerosOK

关闭REGEDT32/REGEDIT并重新启动以删除文件


为了子孙后代,不知羞耻地从中窃取。

杀死其他进程不是一件健康的事情。如果您的场景涉及卸载之类的内容,您可以使用在下次重新启动时将文件标记为删除


如果您确实需要删除另一个进程正在使用的文件,我建议您在考虑任何解决方案之前重新考虑实际问题。

如果您希望以编程方式执行此操作。我不确定。。。我真的建议不要这样做。 如果你只是在自己的机器上排除故障,你能帮你吗

运行它,使用Find Handle命令,我想它在Find或Handle菜单中,然后搜索文件名。一旦找到手柄,就可以强制关闭它们

然后可以删除该文件,依此类推


注意,这样做可能会导致拥有句柄的程序行为异常,因为您刚刚从它下面拔出了众所周知的地毯,但是当您调试自己的错误代码时,它工作得很好,或者当VisualStudio/windows资源管理器被破坏,即使您早就告诉他们关闭文件句柄,但仍不释放文件句柄时。。。叹气:-

哦,我几年前使用的一个大技巧是Windows不允许删除文件,但允许移动文件

伪排序代码:

mv %WINDIR%\System32\mfc42.dll %WINDIR\System32\mfc42.dll.old
Install new mfc42.dll
Tell user to save work and restart applications

当应用程序重新启动时,注意我们不需要重新启动机器,它们加载了新的mfc42.dll,一切正常。再加上在下次整个系统重新启动时删除旧文件的挂起文件操作,效果非常好。

典型的方法如下。你说过你想用C来做这件事,所以现在

如果不知道哪个进程锁定了文件,则需要检查每个进程的句柄列表,并查询每个句柄以确定它是否标识了锁定的文件。在C中执行此操作可能需要P/Invoke或中介C++/CLI来调用您需要的本机API。 一旦确定了哪些进程锁定了文件,就需要安全地向进程中注入一个小型本机DLL,也可以注入一个托管DLL,但这更麻烦,因为您必须启动或附加到.NET运行时。 该引导DLL然后使用CloseHandle关闭句柄,等等。 本质上:解除锁定文件的锁定的方法是将DLL文件注入有问题进程的地址空间,然后自己关闭它。您可以使用本机代码或托管代码来实现这一点。不管怎样,您都需要少量的本机代码,或者至少对相同的代码进行P/Invoke

有用链接:


祝你好运

这看起来很有希望。一种终止文件句柄的方法


使用Orion Edwards建议,我下载了Sysinternals,这反过来让我发现,我在删除文件时遇到困难的文件实际上不是由Excel.Applications对象持有的,而是我的C代码send mail代码创建了一个附件对象,该对象打开了该文件的句柄

看到这一点后,我非常简单地调用了附件对象的dispose方法,然后释放了句柄

Sysinternals资源管理器允许我发现它与VisualStudio2005调试器一起使用


我强烈推荐这个工具

您可以使用提供完整文件路径的代码,它将返回锁定该文件的任何内容的列表:

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;
    }
}
或网络计算机:

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();
        }
    }
}
参考资料:


请注意此MSDN备注:MOVEFILE\u D
ELAY_UNTIL_REBOOT-…仅当进程位于属于administrators组或LocalSystem帐户的用户上下文中时,才能使用此值…这也是我的问题。谢谢你相关的-
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();
        }
    }
}