code_junkie

Is It Possible To Raise An Event When A File Becomes Accessible?

Nov 10th, 2011
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. Public Sub WriteToFile(ByVal FilePath As String, ByVal FileName As String, ByVal Data() As Byte)
  2. Dim FileOpen As Boolean
  3. Dim File As System.IO.FileStream = Nothing
  4. Dim StartTime As DateTime
  5. Dim MaxWaitSeconds As Integer = 120
  6.  
  7. StartTime = DateTime.Now
  8.  
  9. FileOpen = False
  10.  
  11. Do
  12. Try
  13. File = New System.IO.FileStream(FilePath & FileName, IO.FileMode.Append)
  14. FileOpen = True
  15.  
  16. Catch ex As Exception
  17.  
  18. If DateTime.Now.Subtract(StartTime).TotalSeconds > MaxWaitSeconds Then
  19. Throw New Exception("Waited more than " & MaxWaitSeconds & " To Open File.")
  20. Else
  21. Dim FileWatch As System.IO.FileSystemWatcher
  22.  
  23. FileWatch = New System.IO.FileSystemWatcher(FilePath, FileName)
  24. FileWatch.WaitForChanged(IO.WatcherChangeTypes.Changed,5000)
  25. End If
  26.  
  27. FileOpen = False
  28.  
  29. End Try
  30.  
  31. Loop While Not FileOpen
  32.  
  33. If FileOpen Then
  34. File.Write(Data, 0, Data.Length)
  35. File.Close()
  36. End If
  37. End Sub
  38.  
  39. using (var watcher = new FileSystemWatcher(MatlabPath, fileName))
  40. {
  41. var wait = new EventWaitHandle(false, EventResetMode.AutoReset);
  42. watcher.EnableRaisingEvents = true;
  43. watcher.Changed += delegate(object sender, FileSystemEventArgs e)
  44. {
  45. wait.Set();
  46. };
  47. if (!wait.WaitOne(MillissecondsTimeout))
  48. {
  49. throw new TimeoutException();
  50. }
  51. }
Add Comment
Please, Sign In to add comment