<p>What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?</p>

<p>I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the <em>file created</em> event fires before the other process has finished writing the file.</p>

<p>The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.</p>

<p>Edit: After trying out some of the solutions below, I ended up changing the <em>system</em> so that all files wrote to <code>Path.GetTempFileName()</code>, then performed a <code>File.Move()</code> to the final location. As soon as the <code>FileSystemWatcher</code> event fired, the file was already complete.</p>

[{'answer_id': 50753, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 2, 'selected': False, 'text': '<p>One of the techniques I used some time back was to write my own function. Basically catch the exception and retry using a timer which you can fire for a specified duration. If there is a better way, please share.</p>\n'}, {'answer_id': 50765, 'author': 'harpo', 'author_id': 4525, 'author_profile': 'https://Stackoverflow.com/users/4525', 'pm_score': 1, 'selected': False, 'text': "<p>I don't know what you're using to determine the file's lock status, but something like this should do it.</p>\n\n<pre>\nwhile (true)\n{\n    try {\n        stream = File.Open( fileName, fileMode );\n        break;\n    }\n    catch( FileIOException ) {\n\n        // check whether it's a lock problem\n\n        Thread.Sleep( 100 );\n    }\n}\n</pre>\n"}, {'answer_id': 50776, 'author': 'Guy Starbuck', 'author_id': 2194, 'author_profile': 'https://Stackoverflow.com/users/2194', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created.aspx" rel="nofollow noreferrer">MSDN</a>: </p>\n\n<blockquote>\n  <p>The OnCreated event is raised as soon\n  as a file is created. If a file is\n  being copied or transferred into a\n  watched directory, the OnCreated event\n  will be raised immediately, followed\n  by one or more OnChanged events.</p>\n</blockquote>\n\n<p>Your FileSystemWatcher could be modified so that it doesn\'t do its read/rename during the "OnCreated" event, but rather:</p>\n\n<ol>\n<li>Spanws a thread that polls the file status until it is not locked (using a FileInfo object)</li>\n<li>Calls back into the service to process the file as soon as it determines the file is no longer locked and is ready to go</li>\n</ol>\n'}, {'answer_id': 50800, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 7, 'selected': True, 'text': '<p>This was the answer I gave on a <a href="https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app#41559">related question</a>:</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Blocks until the file is not locked any more.\n    /// &lt;/summary&gt;\n    /// &lt;param name="fullPath"&gt;&lt;/param&gt;\n    bool WaitForFile(string fullPath)\n    {\n        int numTries = 0;\n        while (true)\n        {\n            ++numTries;\n            try\n            {\n                // Attempt to open the file exclusively.\n                using (FileStream fs = new FileStream(fullPath,\n                    FileMode.Open, FileAccess.ReadWrite, \n                    FileShare.None, 100))\n                {\n                    fs.ReadByte();\n\n                    // If we got this far the file is ready\n                    break;\n                }\n            }\n            catch (Exception ex)\n            {\n                Log.LogWarning(\n                   "WaitForFile {0} failed to get an exclusive lock: {1}", \n                    fullPath, ex.ToString());\n\n                if (numTries &gt; 10)\n                {\n                    Log.LogWarning(\n                        "WaitForFile {0} giving up after 10 tries", \n                        fullPath);\n                    return false;\n                }\n\n                // Wait for the lock to be released\n                System.Threading.Thread.Sleep(500);\n            }\n        }\n\n        Log.LogTrace("WaitForFile {0} returning true after {1} tries",\n            fullPath, numTries);\n        return true;\n    }\n</code></pre>\n'}, {'answer_id': 50933, 'author': 'Jonathan Allen', 'author_id': 5274, 'author_profile': 'https://Stackoverflow.com/users/5274', 'pm_score': -1, 'selected': False, 'text': "<p>I do it the same way as Gulzar, just keep trying with a loop.</p>\n\n<p>In fact I don't even bother with the file system watcher. Polling a network drive for new files once a minute is cheap.</p>\n"}, {'answer_id': 51001, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': "<p>In most cases simple approach like @harpo suggested will work.  You can develop more sophisticated code using this approach: </p>\n\n<ul>\n<li>Find all opened handles for selected file using SystemHandleInformation\\SystemProcessInformation</li>\n<li>Subclass WaitHandle class to gain access to it's internal handle</li>\n<li>Pass found handles wrapped in subclassed WaitHandle to WaitHandle.WaitAny method</li>\n</ul>\n"}, {'answer_id': 51006, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': 3, 'selected': False, 'text': '<p>For this particular application directly observing the file will inevitably lead to a hard to trace bug, especially when the file size increases. Here are two different strategies that will work.</p>\n\n<ul>\n<li>Ftp two files but only watch one.  For example send the files important.txt and important.finish.  Only watch for the finish file but process the txt.</li>\n<li>FTP one file but rename it when done.  For example send important.wait and have the sender rename it to important.txt when finished.</li>\n</ul>\n\n<p>Good luck!</p>\n'}, {'answer_id': 1171540, 'author': 'Ralph Shillington', 'author_id': 81514, 'author_profile': 'https://Stackoverflow.com/users/81514', 'pm_score': -1, 'selected': False, 'text': "<p>How about this as an option:</p>\n\n<pre><code>private void WaitOnFile(string fileName)\n{\n    FileInfo fileInfo = new FileInfo(fileName);\n    for (long size = -1; size != fileInfo.Length; fileInfo.Refresh())\n    {\n        size = fileInfo.Length;\n        System.Threading.Thread.Sleep(1000);\n    }\n}\n</code></pre>\n\n<p>Of course if the filesize is preallocated on the create you'd get a false positive.</p>\n"}, {'answer_id': 1247326, 'author': 'user152791', 'author_id': 152791, 'author_profile': 'https://Stackoverflow.com/users/152791', 'pm_score': 4, 'selected': False, 'text': '<p>I threw together a helper class for these sorts of things.  It will work if you have control over everything that would access the file.  If you\'re expecting contention from a bunch of other things, then this is pretty worthless.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Threading;\n\n/// &lt;summary&gt;\n/// This is a wrapper aroung a FileStream.  While it is not a Stream itself, it can be cast to\n/// one (keep in mind that this might throw an exception).\n/// &lt;/summary&gt;\npublic class SafeFileStream: IDisposable\n{\n    #region Private Members\n    private Mutex m_mutex;\n    private Stream m_stream;\n    private string m_path;\n    private FileMode m_fileMode;\n    private FileAccess m_fileAccess;\n    private FileShare m_fileShare;\n    #endregion//Private Members\n\n    #region Constructors\n    public SafeFileStream(string path, FileMode mode, FileAccess access, FileShare share)\n    {\n        m_mutex = new Mutex(false, String.Format("Global\\\\{0}", path.Replace(\'\\\\\', \'/\')));\n        m_path = path;\n        m_fileMode = mode;\n        m_fileAccess = access;\n        m_fileShare = share;\n    }\n    #endregion//Constructors\n\n    #region Properties\n    public Stream UnderlyingStream\n    {\n        get\n        {\n            if (!IsOpen)\n                throw new InvalidOperationException("The underlying stream does not exist - try opening this stream.");\n            return m_stream;\n        }\n    }\n\n    public bool IsOpen\n    {\n        get { return m_stream != null; }\n    }\n    #endregion//Properties\n\n    #region Functions\n    /// &lt;summary&gt;\n    /// Opens the stream when it is not locked.  If the file is locked, then\n    /// &lt;/summary&gt;\n    public void Open()\n    {\n        if (m_stream != null)\n            throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n        m_mutex.WaitOne();\n        m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n    }\n\n    public bool TryOpen(TimeSpan span)\n    {\n        if (m_stream != null)\n            throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n        if (m_mutex.WaitOne(span))\n        {\n            m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n            return true;\n        }\n        else\n            return false;\n    }\n\n    public void Close()\n    {\n        if (m_stream != null)\n        {\n            m_stream.Close();\n            m_stream = null;\n            m_mutex.ReleaseMutex();\n        }\n    }\n\n    public void Dispose()\n    {\n        Close();\n        GC.SuppressFinalize(this);\n    }\n\n    public static explicit operator Stream(SafeFileStream sfs)\n    {\n        return sfs.UnderlyingStream;\n    }\n    #endregion//Functions\n}\n</code></pre>\n\n<p>It works using a named mutex.  Those wishing to access the file attempt to acquire control of the named mutex, which shares the name of the file (with the \'\\\'s turned into \'/\'s).  You can either use Open(), which will stall until the mutex is accessible or you can use TryOpen(TimeSpan), which tries to acquire the mutex for the given duration and returns false if it cannot acquire within the time span.  This should most likely be used inside a using block, to ensure that locks are released properly, and the stream (if open) will be properly disposed when this object is disposed.</p>\n\n<p>I did a quick test with ~20 things to do various reads/writes of the file and saw no corruption.  Obviously it\'s not very advanced, but it should work for the majority of simple cases.</p>\n'}, {'answer_id': 3677960, 'author': 'mafu', 'author_id': 39590, 'author_profile': 'https://Stackoverflow.com/users/39590', 'pm_score': 6, 'selected': False, 'text': "<p>Starting from Eric's answer, I included some improvements to make the code far more compact and reusable. Hope it's useful.</p>\n\n<pre><code>FileStream WaitForFile (string fullPath, FileMode mode, FileAccess access, FileShare share)\n{\n    for (int numTries = 0; numTries &lt; 10; numTries++) {\n        FileStream fs = null;\n        try {\n            fs = new FileStream (fullPath, mode, access, share);\n            return fs;\n        }\n        catch (IOException) {\n            if (fs != null) {\n                fs.Dispose ();\n            }\n            Thread.Sleep (50);\n        }\n    }\n\n    return null;\n}\n</code></pre>\n"}, {'answer_id': 5441631, 'author': 'Simon Mourier', 'author_id': 403671, 'author_profile': 'https://Stackoverflow.com/users/403671', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a generic code to do this, independant from the file operation itself. This is an example on how to use it:</p>\n\n<pre><code>WrapSharingViolations(() =&gt; File.Delete(myFile));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>WrapSharingViolations(() =&gt; File.Copy(mySourceFile, myDestFile));\n</code></pre>\n\n<p>You can also define the retry count, and the wait time between retries.</p>\n\n<p>NOTE: Unfortunately, the underlying Win32 error (ERROR_SHARING_VIOLATION) is not exposed with .NET, so I have added a small hack function (<code>IsSharingViolation</code>) based on reflection mechanisms to check this.</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Wraps sharing violations that could occur on a file IO operation.\n    /// &lt;/summary&gt;\n    /// &lt;param name="action"&gt;The action to execute. May not be null.&lt;/param&gt;\n    public static void WrapSharingViolations(WrapSharingViolationsCallback action)\n    {\n        WrapSharingViolations(action, null, 10, 100);\n    }\n\n    /// &lt;summary&gt;\n    /// Wraps sharing violations that could occur on a file IO operation.\n    /// &lt;/summary&gt;\n    /// &lt;param name="action"&gt;The action to execute. May not be null.&lt;/param&gt;\n    /// &lt;param name="exceptionsCallback"&gt;The exceptions callback. May be null.&lt;/param&gt;\n    /// &lt;param name="retryCount"&gt;The retry count.&lt;/param&gt;\n    /// &lt;param name="waitTime"&gt;The wait time in milliseconds.&lt;/param&gt;\n    public static void WrapSharingViolations(WrapSharingViolationsCallback action, WrapSharingViolationsExceptionsCallback exceptionsCallback, int retryCount, int waitTime)\n    {\n        if (action == null)\n            throw new ArgumentNullException("action");\n\n        for (int i = 0; i &lt; retryCount; i++)\n        {\n            try\n            {\n                action();\n                return;\n            }\n            catch (IOException ioe)\n            {\n                if ((IsSharingViolation(ioe)) &amp;&amp; (i &lt; (retryCount - 1)))\n                {\n                    bool wait = true;\n                    if (exceptionsCallback != null)\n                    {\n                        wait = exceptionsCallback(ioe, i, retryCount, waitTime);\n                    }\n                    if (wait)\n                    {\n                        System.Threading.Thread.Sleep(waitTime);\n                    }\n                }\n                else\n                {\n                    throw;\n                }\n            }\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Defines a sharing violation wrapper delegate.\n    /// &lt;/summary&gt;\n    public delegate void WrapSharingViolationsCallback();\n\n    /// &lt;summary&gt;\n    /// Defines a sharing violation wrapper delegate for handling exception.\n    /// &lt;/summary&gt;\n    public delegate bool WrapSharingViolationsExceptionsCallback(IOException ioe, int retry, int retryCount, int waitTime);\n\n    /// &lt;summary&gt;\n    /// Determines whether the specified exception is a sharing violation exception.\n    /// &lt;/summary&gt;\n    /// &lt;param name="exception"&gt;The exception. May not be null.&lt;/param&gt;\n    /// &lt;returns&gt;\n    ///     &lt;c&gt;true&lt;/c&gt; if the specified exception is a sharing violation exception; otherwise, &lt;c&gt;false&lt;/c&gt;.\n    /// &lt;/returns&gt;\n    public static bool IsSharingViolation(IOException exception)\n    {\n        if (exception == null)\n            throw new ArgumentNullException("exception");\n\n        int hr = GetHResult(exception, 0);\n        return (hr == -2147024864); // 0x80070020 ERROR_SHARING_VIOLATION\n\n    }\n\n    /// &lt;summary&gt;\n    /// Gets the HRESULT of the specified exception.\n    /// &lt;/summary&gt;\n    /// &lt;param name="exception"&gt;The exception to test. May not be null.&lt;/param&gt;\n    /// &lt;param name="defaultValue"&gt;The default value in case of an error.&lt;/param&gt;\n    /// &lt;returns&gt;The HRESULT value.&lt;/returns&gt;\n    public static int GetHResult(IOException exception, int defaultValue)\n    {\n        if (exception == null)\n            throw new ArgumentNullException("exception");\n\n        try\n        {\n            const string name = "HResult";\n            PropertyInfo pi = exception.GetType().GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance); // CLR2\n            if (pi == null)\n            {\n                pi = exception.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance); // CLR4\n            }\n            if (pi != null)\n                return (int)pi.GetValue(exception, null);\n        }\n        catch\n        {\n        }\n        return defaultValue;\n    }\n</code></pre>\n'}, {'answer_id': 6626484, 'author': 'Rudi', 'author_id': 835615, 'author_profile': 'https://Stackoverflow.com/users/835615', 'pm_score': 2, 'selected': False, 'text': '<p>Ad to transfer process trigger file SameNameASTrasferedFile.trg\nthat is created after  file transmission is completed.</p>\n\n<p>Then setup FileSystemWatcher  that will fire event only on *.trg file.</p>\n'}, {'answer_id': 14467767, 'author': 'Bernhard Hochgatterer', 'author_id': 2001739, 'author_profile': 'https://Stackoverflow.com/users/2001739', 'pm_score': -1, 'selected': False, 'text': '<p>Simply use the <strong>Changed</strong> event with the NotifyFilter <strong>NotifyFilters.LastWrite</strong>:</p>\n\n<pre><code>var watcher = new FileSystemWatcher {\n      Path = @"c:\\temp\\test",\n      Filter = "*.xml",\n      NotifyFilter = NotifyFilters.LastWrite\n};\nwatcher.Changed += watcher_Changed; \nwatcher.EnableRaisingEvents = true;\n</code></pre>\n'}, {'answer_id': 22178178, 'author': 'Jahmal23', 'author_id': 3380046, 'author_profile': 'https://Stackoverflow.com/users/3380046', 'pm_score': -1, 'selected': False, 'text': '<p>I ran into a similar issue when adding an outlook attachment.  "Using" saved the day.</p>\n\n<pre><code>string fileName = MessagingBLL.BuildPropertyAttachmentFileName(currProp);\n\n                //create a temporary file to send as the attachment\n                string pathString = Path.Combine(Path.GetTempPath(), fileName);\n\n                //dirty trick to make sure locks are released on the file.\n                using (System.IO.File.Create(pathString)) { }\n\n                mailItem.Subject = MessagingBLL.PropertyAttachmentSubject;\n                mailItem.Attachments.Add(pathString, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);\n</code></pre>\n'}, {'answer_id': 42782410, 'author': 'Florian K', 'author_id': 6754146, 'author_profile': 'https://Stackoverflow.com/users/6754146', 'pm_score': 1, 'selected': False, 'text': '<p>A possible solution would be, to combine a filesystemwatcher with some polling,</p>\n\n<p>get Notified for every Change on a File, and when getting notified check if it is \nlocked as stated in the currently accepted answer: <a href="https://stackoverflow.com/a/50800/6754146">https://stackoverflow.com/a/50800/6754146</a>\nThe code for opening the filestream is copied from the answer and slightly modified:</p>\n\n<pre><code>public static void CheckFileLock(string directory, string filename, Func&lt;Task&gt; callBack)\n{\n    var watcher = new FileSystemWatcher(directory, filename);\n    FileSystemEventHandler check = \n        async (sender, eArgs) =&gt;\n    {\n        string fullPath = Path.Combine(directory, filename);\n        try\n        {\n            // Attempt to open the file exclusively.\n            using (FileStream fs = new FileStream(fullPath,\n                    FileMode.Open, FileAccess.ReadWrite,\n                    FileShare.None, 100))\n            {\n                fs.ReadByte();\n                watcher.EnableRaisingEvents = false;\n                // If we got this far the file is ready\n            }\n            watcher.Dispose();\n            await callBack();\n        }\n        catch (IOException) { }\n    };\n    watcher.NotifyFilter = NotifyFilters.LastWrite;\n    watcher.IncludeSubdirectories = false;\n    watcher.EnableRaisingEvents = true;\n    //Attach the checking to the changed method, \n    //on every change it gets checked once\n    watcher.Changed += check;\n    //Initially do a check for the case it is already released\n    check(null, null);\n}\n</code></pre>\n\n<p>With this way you can Check for a file if its locked and get notified when its closed over the specified callback, this way you avoid the overly aggressive polling and only do the work when it may be actually be closed</p>\n'}, {'answer_id': 67424708, 'author': 'Tyrone Moodley', 'author_id': 3263578, 'author_profile': 'https://Stackoverflow.com/users/3263578', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a similar answer to the above except I added a check to see if the file exists.</p>\n<pre><code>bool WaitForFile(string fullPath)\n        {\n            int numTries = 0;\n            while (true)\n            {\n                //need to add this line to prevent infinite loop\n                if (!File.Exists(fullPath))\n                {\n                    _logger.LogInformation(&quot;WaitForFile {0} returning true - file does not exist&quot;, fullPath);\n                    break;\n                }\n                ++numTries;\n                try\n                {\n                    // Attempt to open the file exclusively.\n                    using (FileStream fs = new FileStream(fullPath,\n                        FileMode.Open, FileAccess.ReadWrite,\n                        FileShare.None, 100))\n                    {\n                        fs.ReadByte();\n\n                        // If we got this far the file is ready\n                        break;\n                    }\n                }\n                catch (Exception ex)\n                {\n                    _logger.LogInformation(\n                       &quot;WaitForFile {0} failed to get an exclusive lock: {1}&quot;,\n                        fullPath, ex.ToString());\n\n                    if (numTries &gt; 10)\n                    {\n                        _logger.LogInformation(\n                            &quot;WaitForFile {0} giving up after 10 tries&quot;,\n                            fullPath);\n                        return false;\n                    }\n\n                    // Wait for the lock to be released\n                    System.Threading.Thread.Sleep(500);\n                }\n            }\n\n            _logger.LogInformation(&quot;WaitForFile {0} returning true after {1} tries&quot;,\n                fullPath, numTries);\n            return true;\n        }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/50744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5548/']