<p>In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.</p>

<p>The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.</p>

<p>Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?</p>

[{'answer_id': 24323, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar problems on some recent work I was doing.</p>\n\n<p>In short, I was trying to write to a file that was locked at the time. I ended up wrapping the write method up so it would automatically try the write again in a few ms after..</p>\n\n<p>Thinking out loud, Can you probe the file for a ReadOnly status? May be worth then having a wrapper for file IO which can stack up delegates for pending file operations or something.. Thoughts?</p>\n'}, {'answer_id': 24336, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': '<p>Use <a href="http://msdn.microsoft.com/en-us/library/aa363858.aspx" rel="nofollow noreferrer">CreateFile</a> in a loop with OPEN_ EXISTING flag and FILE_ ALL_ ACCESS (or you might need only a subset, see <a href="http://msdn.microsoft.com/en-us/library/aa364399(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa364399(VS.85).aspx</a></p>\n\n<p>Examine the handle returned against -1 (INVALID_ HANDLE_ VALUE) for failure.  It\'s still polling, but this will save the cost of an exception throw.</p>\n\n<p>EDIT: this editor/markup can\'t handle underscores! bah!</p>\n'}, {'answer_id': 24429, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 3, 'selected': False, 'text': '<p>You can use a file system watcher to check when the file has been changed.  It only becomes "changed" after whichever program had the file previously closes the file.  I know you asked for C#, but my VB.Net is much better. Hope you or someone else can translate.</p>\n\n<p>It tries to open the file, if it isn\'t available, it adds a watcher, and waits for the file to be changed.  After the file is changed, it tries to open again.  It throws an exception if it waits more than 120 seconds, because you may get caught in a situation where the file is never released.  Also, I decided to add a timeout of waiting for the file change of 5 seconds, in case of the small possibility that the file was closed prior to the actual file watcher being created.</p>\n\n<pre><code> Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)\n        Dim FileOpen As Boolean\n        Dim File As System.IO.FileStream = Nothing\n        Dim StartTime As DateTime\n        Dim MaxWaitSeconds As Integer = 120\n\n        StartTime = DateTime.Now\n\n        FileOpen = False\n\n        Do\n            Try\n                File = New System.IO.FileStream(FilePath &amp; FileName, IO.FileMode.Append)\n                FileOpen = True\n\n            Catch ex As Exception\n\n                If DateTime.Now.Subtract(StartTime).TotalSeconds &gt; MaxWaitSeconds Then\n                    Throw New Exception("Waited more than " &amp; MaxWaitSeconds &amp; " To Open File.")\n                Else\n                    Dim FileWatch As System.IO.FileSystemWatcher\n\n                    FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)\n                    FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)\n                End If\n\n                FileOpen = False\n\n            End Try\n\n        Loop While Not FileOpen\n\n        If FileOpen Then\n            File.Write(Data, 0, Data.Length)\n            File.Close()\n        End If\n    End Sub\n</code></pre>\n'}, {'answer_id': 1115109, 'author': 'Jader Dias', 'author_id': 48465, 'author_profile': 'https://Stackoverflow.com/users/48465', 'pm_score': 0, 'selected': False, 'text': "<p>Kibbe answer seems right but didn't worked for me. It seems that the FileSystemWatcher has a bug. So I wrote my own WaitForChanged:</p>\n\n<pre><code>using (var watcher = new FileSystemWatcher(MatlabPath, fileName))\n{\n    var wait = new EventWaitHandle(false, EventResetMode.AutoReset);\n    watcher.EnableRaisingEvents = true;\n    watcher.Changed += delegate(object sender, FileSystemEventArgs e)\n    {\n       wait.Set();\n    };\n    if (!wait.WaitOne(MillissecondsTimeout))\n    {\n        throw new TimeoutException();\n    }\n }\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/24315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392/']