Advertisement
Guest User

Untitled

a guest
May 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. using System;
  2. using ObjCRuntime;
  3. using Foundation;
  4. using CoreFoundation;
  5. using System.IO;
  6.  
  7. namespace LoadRuntimeXAML.iOS
  8. {
  9. public class FileWatcher : IDisposable
  10. {
  11. public void Dispose()
  12. {
  13. StopFileMonitoring();
  14. }
  15.  
  16. public FileWatcher(string filePath) : base(filePath)
  17. {
  18. Path = filePath;
  19. StartMonitoringFile();
  20. }
  21.  
  22.  
  23. private void StartMonitoringFile()
  24. {
  25. fileMonitorSource?.Cancel();
  26. fileMonitorSource = null;
  27.  
  28. var stream = File.OpenRead(Path);
  29.  
  30. int fileDescriptor = stream.SafeFileHandle.DangerousGetHandle().ToInt32();
  31. fileMonitorSource = new DispatchSource.VnodeMonitor(fileDescriptor, VnodeMonitorKind.Delete | VnodeMonitorKind.Extend | VnodeMonitorKind.Write, DispatchQueue.MainQueue);
  32. fileMonitorSource.SetEventHandler(() =>
  33. {
  34. var observedEvents = fileMonitorSource.ObservedEvents;
  35. Console.WriteLine("Vnode monitor event: {0} for file: {1}", observedEvents, Path);
  36. if (observedEvents.HasFlag(VnodeMonitorKind.Delete))
  37. {
  38. FileDeleted();
  39. }
  40.  
  41. FileChangedEvent?.Invoke(this, Path);
  42. });
  43.  
  44. fileMonitorSource.SetCancelHandler(() =>
  45. {
  46. stream.Close();
  47. });
  48.  
  49. fileMonitorSource.Resume();
  50. }
  51. private void StopFileMonitoring()
  52. {
  53. fileMonitorSource?.Cancel();
  54. fileMonitorSource = null;
  55. }
  56.  
  57.  
  58. private void FileDeleted()
  59. {
  60. StopFileMonitoring();
  61.  
  62. if (File.Exists(Path))
  63. {
  64. StartMonitoringFile();
  65. return;
  66. }
  67. else
  68. {
  69. // Some editors delete and replace the file on save, instead of actually saving and modifying the file.
  70. DispatchQueue.MainQueue.DispatchAfter(new DispatchTime(DispatchTime.Now, TimeSpan.FromSeconds(0.5)), () =>
  71. {
  72. FileDeleted();
  73. });
  74. }
  75. }
  76.  
  77. private DispatchSource.VnodeMonitor fileMonitorSource;
  78.  
  79. public string Path { get; }
  80.  
  81. public event FileChanged FileChangedEvent;
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement