<p>I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using <code>File.Delete()</code>.</p>

[{'answer_id': 1043, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 3, 'selected': False, 'text': '<p>You can use this program, <a href="https://learn.microsoft.com/en-gb/sysinternals/downloads/handle" rel="nofollow noreferrer">Handle</a>, to find which process has the lock on your file. It\'s a command-line tool, so I guess you use the output from that. I\'m not sure about finding it programmatically.</p>\n\n<p>If deleting the file can wait, you could specify it for deletion when your computer next starts up:</p>\n\n<ol>\n<li><p>Start <code>REGEDT32 (W2K)</code> or <code>REGEDIT (WXP)</code> and navigate to:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\n</code></pre></li>\n<li><p>W2K and WXP</p>\n\n<ul>\n<li><p><strong>W2K:</strong><br/>Edit<br/>Add Value...<br/>Data Type: <code>REG_MULTI_SZ</code><br/>Value Name: <code>PendingFileRenameOperations</code><br/><kbd>OK</kbd></p></li>\n<li><p><strong>WXP:</strong><br/>Edit<br/>New<br/>Multi-String Value<br/><kbd>enter</kbd><br/>\n<code>PendingFileRenameOperations</code></p></li>\n</ul></li>\n<li><p>In the Data area, enter <code>"\\??\\" + filename</code> to be deleted. LFNs may\nbe entered without being embedded in quotes. To delete <code>C:\\Long Directory Name\\Long File Name.exe</code>, enter the following data:</p>\n\n<pre><code>\\??\\C:\\Long Directory Name\\Long File Name.exe\n</code></pre>\n\n<p>Then press <kbd>OK</kbd>.</p></li>\n<li><p>The "destination file name" is a null (zero) string. It is entered\nas follows:</p>\n\n<ul>\n<li><p><strong>W2K:</strong><br/>Edit<br/>Binary<br/>select Data Format: Hex<br/>click at the end of the hex string<br/>enter 0000 (four zeros)<br/><kbd>OK</kbd></p></li>\n<li><p><strong>WXP:</strong><br/>Right-click the value<br/>choose "Modify Binary Data"<br/>click at the end of the hex string<br/>enter 0000 (four zeros)<br/><kbd>OK</kbd></p></li>\n</ul></li>\n<li><p>Close <code>REGEDT32/REGEDIT</code> and reboot to delete the file.</p></li>\n</ol>\n\n<p><sup>(Shamelessly stolen from <a href="http://www.pcreview.co.uk/forums/thread-1581158.php" rel="nofollow noreferrer">some random forum</a>, for posterity\'s sake.)</sup></p>\n'}, {'answer_id': 1044, 'author': 'Ishmaeel', 'author_id': 227, 'author_profile': 'https://Stackoverflow.com/users/227', 'pm_score': 6, 'selected': True, 'text': '<p>Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa" rel="nofollow noreferrer"><strong><code>MoveFileEx</code></strong> API function</a> to mark the file for deletion upon next reboot.</p>\n\n<p>If it appears that you really need to delete a file in use by another process, I\'d recommend re-considering the actual problem before considering any solutions.</p>\n'}, {'answer_id': 1049, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to do it programmatically. I\'m not sure... and I\'d really recommend against it.\nIf you\'re just troubleshooting stuff on your own machine, <a href="https://learn.microsoft.com/en-gb/sysinternals/downloads/process-explorer" rel="nofollow noreferrer">SysInternals Process Explorer</a> can help you</p>\n\n<p>Run it, use the Find Handle command (I think it\'s either in the find or handle menu), and search for the name of your file. Once the handle(s) is found, you can forcibly close them.</p>\n\n<p>You can then delete the file and so on.</p>\n\n<p><strong>Beware</strong>, doing this may cause the program which owns the handles to behave strangely, as you\'ve just pulled the proverbial rug out from under it, but it works well when you are debugging your own errant code, or when visual studio/windows explorer is being crapped and not releasing file handles even though you told them to close the file ages ago... sigh :-)</p>\n'}, {'answer_id': 1050, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 2, 'selected': False, 'text': "<p>Oh, one big hack I employed years ago, is that Windows won't let you <em>delete</em> files, but it does let you <em>move</em> them.</p>\n\n<p>Pseudo-sort-of-code:</p>\n\n<pre><code>mv %WINDIR%\\System32\\mfc42.dll %WINDIR\\System32\\mfc42.dll.old\nInstall new mfc42.dll\nTell user to save work and restart applications\n</code></pre>\n\n<p>When the applications restarted (note we didn't need to reboot the machine), they loaded the new <code>mfc42.dll</code>, and all was well. That, coupled with <code>PendingFileOperations</code> to delete the old one the next time the whole system restarted, worked pretty well.</p>\n"}, {'answer_id': 1051, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>The typical method is as follows. You\'ve said you want to do this in C# so here goes...</p>\n\n<ol>\n<li>If you don\'t know which process has the file locked, you\'ll need to examine each process\'s handle list, and query each handle to determine if it identifies the locked file. Doing this in C# will likely require P/Invoke or an intermediary C++/CLI to call the native APIs you\'ll need.</li>\n<li>Once you\'ve figured out which process(es) have the file locked, you\'ll need to safely inject a small native DLL into the process (you can also inject a managed DLL, but this is messier, as you then have to start or attach to the .NET runtime).</li>\n<li>That bootstrap DLL then closes the handle using CloseHandle, etc.</li>\n</ol>\n\n<p>Essentially: the way to unlock a "locked" file is to inject a DLL file into the offending process\'s address space and close it yourself. You can do this using native or managed code. No matter what, you\'re going to need a small amount of native code or at least P/Invoke into the same.</p>\n\n<p>Helpful links:</p>\n\n<ul>\n<li><em><a href="http://www.codeproject.com/KB/threads/winspy.aspx" rel="nofollow noreferrer">Three Ways to Inject Your Code into Another Process</a></em></li>\n<li><em><a href="http://damianblog.com/2008/07/02/net-code-injection/" rel="nofollow noreferrer">.NET Code Injection</a></em></li>\n</ul>\n\n<p>Good luck!</p>\n'}, {'answer_id': 587053, 'author': 'solrevdev', 'author_id': 2041, 'author_profile': 'https://Stackoverflow.com/users/2041', 'pm_score': 2, 'selected': False, 'text': '<p>This looks promising. A way of killing the file handle....</p>\n\n<p><a href="http://www.timstall.com/2009/02/killing-file-handles-but-not-process.html" rel="nofollow noreferrer">http://www.timstall.com/2009/02/killing-file-handles-but-not-process.html</a></p>\n'}, {'answer_id': 610598, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Using Orion Edwards advice I downloaded the Sysinternals <a href="https://en.wikipedia.org/wiki/Process_Explorer" rel="nofollow noreferrer">Process&nbsp;Explorer</a> which in turn allowed me to discover that the file I was having difficulties deleting was in fact being held not by the <code>Excel.Applications</code> object I thought, but rather the fact that my C# code send mail code had created an Attachment object that left a handle to this file open.</p>\n\n<p>Once I saw this, I quite simple called on the dispose method of the Attachment object, and the handle was released.</p>\n\n<p>The Sysinternals explorer allowed me to discover this used in conjunction with the Visual&nbsp;Studio&nbsp;2005 debugger.</p>\n\n<p>I highly recommend this tool!</p>\n'}, {'answer_id': 41902743, 'author': 'vapcguy', 'author_id': 1181535, 'author_profile': 'https://Stackoverflow.com/users/1181535', 'pm_score': 2, 'selected': False, 'text': '<p>You can use code that you supply the full file path to, and it will return a <code>List&lt;Processes&gt;</code> of anything locking that file:</p>\n\n<pre><code>using System.Runtime.InteropServices;\nusing System.Diagnostics;\n\nstatic public class FileUtil\n{\n    [StructLayout(LayoutKind.Sequential)]\n    struct RM_UNIQUE_PROCESS\n    {\n        public int dwProcessId;\n        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;\n    }\n\n    const int RmRebootReasonNone = 0;\n    const int CCH_RM_MAX_APP_NAME = 255;\n    const int CCH_RM_MAX_SVC_NAME = 63;\n\n    enum RM_APP_TYPE\n    {\n        RmUnknownApp = 0,\n        RmMainWindow = 1,\n        RmOtherWindow = 2,\n        RmService = 3,\n        RmExplorer = 4,\n        RmConsole = 5,\n        RmCritical = 1000\n    }\n\n    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n    struct RM_PROCESS_INFO\n    {\n        public RM_UNIQUE_PROCESS Process;\n\n        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]\n        public string strAppName;\n\n        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]\n        public string strServiceShortName;\n\n        public RM_APP_TYPE ApplicationType;\n        public uint AppStatus;\n        public uint TSSessionId;\n        [MarshalAs(UnmanagedType.Bool)]\n        public bool bRestartable;\n    }\n\n    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]\n    static extern int RmRegisterResources(uint pSessionHandle,\n                                          UInt32 nFiles,\n                                          string[] rgsFilenames,\n                                          UInt32 nApplications,\n                                          [In] RM_UNIQUE_PROCESS[] rgApplications,\n                                          UInt32 nServices,\n                                          string[] rgsServiceNames);\n\n    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]\n    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);\n\n    [DllImport("rstrtmgr.dll")]\n    static extern int RmEndSession(uint pSessionHandle);\n\n    [DllImport("rstrtmgr.dll")]\n    static extern int RmGetList(uint dwSessionHandle,\n                                out uint pnProcInfoNeeded,\n                                ref uint pnProcInfo,\n                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,\n                                ref uint lpdwRebootReasons);\n\n    /// &lt;summary&gt;\n    /// Find out what process(es) have a lock on the specified file.\n    /// &lt;/summary&gt;\n    /// &lt;param name="path"&gt;Path of the file.&lt;/param&gt;\n    /// &lt;returns&gt;Processes locking the file&lt;/returns&gt;\n    /// &lt;remarks&gt;See also:\n    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx\n    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)\n    /// \n    /// &lt;/remarks&gt;\n    static public List&lt;Process&gt; WhoIsLocking(string path)\n    {\n        uint handle;\n        string key = Guid.NewGuid().ToString();\n        List&lt;Process&gt; processes = new List&lt;Process&gt;();\n\n        int res = RmStartSession(out handle, 0, key);\n        if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");\n\n        try\n        {\n            const int ERROR_MORE_DATA = 234;\n            uint pnProcInfoNeeded = 0,\n                 pnProcInfo = 0,\n                 lpdwRebootReasons = RmRebootReasonNone;\n\n            string[] resources = new string[] { path }; // Just checking on one resource.\n\n            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);\n\n            if (res != 0) throw new Exception("Could not register resource.");                                    \n\n            //Note: there\'s a race condition here -- the first call to RmGetList() returns\n            //      the total number of process. However, when we call RmGetList() again to get\n            //      the actual processes this number may have increased.\n            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);\n\n            if (res == ERROR_MORE_DATA)\n            {\n                // Create an array to store the process results\n                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];\n                pnProcInfo = pnProcInfoNeeded;\n\n                // Get the list\n                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);\n                if (res == 0)\n                {\n                    processes = new List&lt;Process&gt;((int)pnProcInfo);\n\n                    // Enumerate all of the results and add them to the \n                    // list to be returned\n                    for (int i = 0; i &lt; pnProcInfo; i++)\n                    {\n                        try\n                        {\n                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));\n                        }\n                        // catch the error -- in case the process is no longer running\n                        catch (ArgumentException) { }\n                    }\n                }\n                else throw new Exception("Could not list processes locking resource.");                    \n            }\n            else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    \n        }\n        finally\n        {\n            RmEndSession(handle);\n        }\n\n        return processes;\n    }\n}\n</code></pre>\n\n<p>Then, iterate the list of processes and close them and delete the files:</p>\n\n<pre><code>    string[] files = Directory.GetFiles(target_dir);\n    List&lt;Process&gt; lstProcs = new List&lt;Process&gt;();\n\n    foreach (string file in files)\n    {\n        lstProcs = ProcessHandler.WhoIsLocking(file);\n        if (lstProcs.Count &gt; 0) // deal with the file lock\n        {\n            foreach (Process p in lstProcs)\n            {\n                if (p.MachineName == ".")\n                    ProcessHandler.localProcessKill(p.ProcessName);\n                else\n                    ProcessHandler.remoteProcessKill(p.MachineName, txtUserName.Text, txtPassword.Password, p.ProcessName);\n            }\n            File.Delete(file);\n        }\n        else\n            File.Delete(file);\n    }\n</code></pre>\n\n<p>And depending on if the file is on the local computer:</p>\n\n<pre><code>public static void localProcessKill(string processName)\n{\n    foreach (Process p in Process.GetProcessesByName(processName))\n    {\n        p.Kill();\n    }\n}\n</code></pre>\n\n<p>or a network computer:</p>\n\n<pre><code>public static void remoteProcessKill(string computerName, string fullUserName, string pword, string processName)\n{\n    var connectoptions = new ConnectionOptions();\n    connectoptions.Username = fullUserName;  // @"YourDomainName\\UserName";\n    connectoptions.Password = pword;\n\n    ManagementScope scope = new ManagementScope(@"\\\\" + computerName + @"\\root\\cimv2", connectoptions);\n\n    // WMI query\n    var query = new SelectQuery("select * from Win32_process where name = \'" + processName + "\'");\n\n    using (var searcher = new ManagementObjectSearcher(scope, query))\n    {\n        foreach (ManagementObject process in searcher.Get()) \n        {\n            process.InvokeMethod("Terminate", null);\n            process.Dispose();\n        }\n    }\n}\n</code></pre>\n\n<p><strong>References:</strong><br>\n<a href="https://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net">How do I find out which process is locking a file using .NET?</a></p>\n\n<p><a href="https://stackoverflow.com/questions/41841590/delete-a-directory-where-someone-has-opened-a-file">Delete a directory where someone has opened a file</a></p>\n'}]
['https://Stackoverflow.com/questions/1040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254/']