FileSystemWatcher 簡單使用


這里看一個文件夾下監測的例子。

首先來看下MSDN上的備注信息。這里網址:http://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher.aspx

使用 FileSystemWatcher 監視指定目錄中的更改。可監視指定目錄中的文件或子目錄的更改。可以創建一個組件來監視本地計算機、網絡驅動器或遠程計算機上的文件。

若要監視所有文件中的更改,請將 Filter 屬性設置為空字符串 ("") 或使用通配符(“*.*”)。若要監視特定的文件,請將 Filter 屬性設置為該文件名。例如,若要監視文件 MyDoc.txt 中的更改,請將 Filter 屬性設置為“MyDoc.txt”。也可以監視特定類型文件中的更改。例如,若要監視文本文件中的更改,請將 Filter 屬性設置為“*.txt”。

可監視目錄或文件中的若干種更改。例如,可監視文件或目錄的 AttributesLastWrite 日期和時間或 Size 方面的更改。通過將 NotifyFilter 屬性設置為 NotifyFilters 值之一來達到此目的。有關可監視的更改類型的更多信息,請參見 NotifyFilters

可監視文件或目錄的重命名、刪除或創建。例如,若要監視文本文件的重命名,請將 Filter 屬性設置為“*.txt”,並使用為其參數指定的 Renamed 來調用 WaitForChanged 方法。

Windows 操作系統在 FileSystemWatcher 創建的緩沖區中通知組件文件發生更改。如果短時間內有很多更改,則緩沖區可能會溢出。這將導致組件失去對目錄更改的跟蹤,並且它將只提供一般性通知。增加緩沖區的大小與 InternalBufferSize 屬性的是成本高昂的,那么,當有來自不能交換到磁盤的未調用的內存,因此,保留緩沖區如小,並且足以不缺少任何文件更改事件。若要避免緩沖區溢出,請使用 NotifyFilter 和 IncludeSubdirectories 屬性,以便可以篩選掉不想要的更改通知。

有關 FileSystemWatcher 的實例的初始屬性值列表,請參見 FileSystemWatcher 構造函數。

使用 FileSystemWatcher 類時,請注意以下事項。

  • 不忽略隱藏文件。

  • 在某些系統中,FileSystemWatcher 使用 8.3 短文件名格式報告文件更改。例如,為“LongFileName.LongExtension”更改可以報告為“LongFil~.Lon”。

  • 此類在應用於所有成員的類級別上包含一個鏈接要求和一個繼承要求。如果直接調用方或派生類不具有完全信任權限,則會引發 SecurityException有關安全要求的詳細信息,請參見 鏈接需求

  • 您可以為 InternalBufferSize 屬性(用於監視網絡上的目錄)設置的最大大小為 64 KB。

   這里自己結合官方寫了個例子,里面肯定有很多東西沒有想到,歡迎各位指正。

 

 

  1  class Program
  2     {
  3        private static  FileSystemWatcher watcher;
  4        private static string logDir = (AppDomain.CurrentDomain.BaseDirectory); //get current project bin dir
  5        private static string logFile = "Log";
  6        private static string sMonitorDir = @"D:\TDDOWNLOAD";
  7        private static string LogExt = "log";  // file suffix
  8 
  9         static void Main(string[] args)
 10         {
 11             Run();
 12         }
 13         [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
 14         public static void Run()
 15         {
 16             watcher = new FileSystemWatcher();
 17 
 18             //需要監測的文件路徑,路徑不存在則創建
 19             DirectoryInfo di = new DirectoryInfo(sMonitorDir);
 20             if (!di.Exists)
 21             {
 22                 di.Create();
 23             }
 24             watcher.Path = sMonitorDir;
 25             //獲取或設置要監視的更改類型。
 26             watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
 27                 | NotifyFilters.LastAccess | NotifyFilters.LastWrite;
 28             watcher.IncludeSubdirectories = true; //是否包含子目錄
 29             watcher.Filter = "*.txt";
 30 
 31             watcher.Changed += new FileSystemEventHandler(OnChanged);
 32             watcher.Created += new FileSystemEventHandler(OnChanged);
 33             watcher.Deleted += new FileSystemEventHandler(OnChanged);
 34             watcher.Renamed += new RenamedEventHandler(OnRenamed);
 35             watcher.Error += new ErrorEventHandler(OnError);
 36 
 37             watcher.EnableRaisingEvents = true;
 38 
 39             Console.Read();
 40         }
 41 
 42         //changeed,deleted,created.
 43         static void OnChanged(object sender, FileSystemEventArgs e)
 44         {
 45             //先將EnableRaisingEvents設置為false然后處理完文件之后再設置為true即可避免觸發多次問題。
 46             watcher.EnableRaisingEvents = false;
 47             //WatcherChangeTypes是一個枚舉
 48             if (WatcherChangeTypes.Changed == e.ChangeType)
 49             {
 50                 Console.WriteLine("File is changed");
 51             }
 52             if (WatcherChangeTypes.Created == e.ChangeType)
 53             {
 54                 Console.WriteLine("File is Created");
 55             }
 56             if (WatcherChangeTypes.Deleted == e.ChangeType)
 57             {
 58                 Console.WriteLine("File is deleted");
 59             }
 60             Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
 61             WriteFile("File: " + e.FullPath + " " + e.ChangeType);
 62             watcher.EnableRaisingEvents = true;
 63         }
 64 
 65         //renamed event
 66         private static void OnRenamed(object source, RenamedEventArgs e)
 67         {
 68             watcher.EnableRaisingEvents = false;
 69             if (WatcherChangeTypes.Renamed == e.ChangeType)
 70             {
 71                 Console.WriteLine("File is renamed");                
 72 
 73             }
 74             Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
 75             WriteFile("File: " + e.FullPath + " " + e.ChangeType);
 76             watcher.EnableRaisingEvents = true;
 77         
 78         }
 79         private static void OnError(object source, ErrorEventArgs e)
 80         {
 81             Console.WriteLine("The FileSystemWatcher has detected an error");
 82 
 83             if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
 84             {
 85                 Console.WriteLine(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
 86                 WriteFile(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
 87             }
 88         }
 89         //write the message to file
 90         private static void WriteFile(string sMessage)
 91         {
 92             try
 93             {
 94                 Log logEntry = new Log(sMessage);
 95                 string logPath = Path.Combine(logDir, logFile, logEntry.LogDate + "." + LogExt);
 96                 if ((logPath.Length > 0) && (!Directory.Exists(logPath)))
 97                 {
 98                     Directory.CreateDirectory(Path.GetDirectoryName(logPath));
 99                 }
100                 // This could be optimised to prevent opening and closing the file for each write
101                 using (FileStream fs = File.Open(logPath, FileMode.Append, FileAccess.Write))
102                 {
103                     using (StreamWriter log = new StreamWriter(fs))
104                     {
105                         log.WriteLine(string.Format("{0}\t{1}", logEntry.LogTime, logEntry.Message));
106                     }
107                 }
108             }
109             catch (Exception ex)
110             {
111                 throw ex;
112             }
113         }
114     }
115     /// <summary>
116     /// A Log class to store the message and the Date and Time the log entry was created
117     /// </summary>
118     public class Log
119     {
120         public string Message { get; set; }
121         public string LogTime { get; set; }
122         public string LogDate { get; set; }
123         public string LogFileName { get; set; }
124         public Log(string message)
125         {
126             Message = message;
127             DateTime curDT = DateTime.Now;
128             LogDate = curDT.ToString("yyyy-MM-dd");
129             LogTime = curDT.ToString("hh:mm:ss.fff tt");
130             LogFileName = curDT.ToString("yyyyMMddhhmmssfff");
131         }
132     }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM