2012-09-05 82 views
2

我想創建一個簡單的應用程序,什麼將所有文件writed到一些目錄到其他目錄。這是我的問題:如果我一次在我的目錄中寫入超過10000個文件(超過1KB的小型.txt文件) - 其中一些文件無法在輸出目錄上移動。我正在使用FileSystemWatcher事件處理程序來解決此問題。這裏是我的代碼示例:從FileSystemWatcher捕獲丟失事件C#

Class MyProgramm 
{ 
    void Process(Object o, FileSystemEventArgs e) 
    { 
     //do something with e.Name file 
    } 
    void main() 
    { 
     var FSW = New FileSystemWatcher{Path = "C:\\InputDir"}; 
     FSW.Created += Process; 
     FSW.EnableRisingEvents = true; 
     Thread.Sleep(Timeout.Infinite); 
    } 
} 

最後,我們得到了一些文件處理,但有些書面文件撐未處理.. 有什麼建議?

+0

的可能重複[FileSystemWatcher的VS輪詢來監視文件更改(http://stackoverflow.com/questions/239988/filesystemwatcher-vs-polling-to-watch-for-file-更改) –

+0

請澄清您的問題。這是FileSystemWatcher無法檢測到移動文件的問題嗎?或者是文件本身無法從輸入轉到輸出目錄? –

+0

看看相關文章http://stackoverflow.com/questions/1286114/detecting-moved-files-using-filesystemwatcher –

回答

0

我有類似的問題與FileSystemWatcher。它似乎很經常地「放下球」。我通過擴展「ServiceBase」來尋求替代解決方案,自從它作爲一個Windows服務上線以來,它始終如一地運行。希望這有助於:

public partial class FileMonitor : ServiceBase 
    { 
     private Timer timer; 
     private long interval; 
     private const string ACCEPTED_FILE_TYPE = "*.csv"; 

     public FileMonitor() 
     {   
      this.ServiceName = "Service"; 
      this.CanStop = true; 
      this.CanPauseAndContinue = true; 
      this.AutoLog = true; 
      this.interval = long.Parse(1000); 
     } 

     public static void Main() 
     { 
      ServiceBase.Run(new FileMonitor()); 
     } 

     protected override void OnStop() 
     { 
      base.OnStop(); 
      this.timer.Dispose(); 
     } 

     protected override void OnStart(string[] args) 
     { 
      AutoResetEvent autoEvent = new AutoResetEvent(false); 
      this.timer = new Timer(new TimerCallback(ProcessNewFiles), autoEvent, interval, Timeout.Infinite); 
     } 

     private void ProcessNewFiles(Object stateInfo) 
     { 
      DateTime start = DateTime.Now; 
      DateTime complete = DateTime.Now; 

      try 
      { 
       string directoryToMonitor = "c:\mydirectory"; 
       DirectoryInfo feedDir = new DirectoryInfo(directoryToMonitor); 
       FileInfo[] feeds = feedDir.GetFiles(ACCEPTED_FILE_TYPE, SearchOption.TopDirectoryOnly);    

       foreach (FileInfo feed in feeds.OrderBy(m => m.LastWriteTime)) 
       { 
        // Do whatever you want to do with the file here 
       } 
      } 
      finally 
      { 
       TimeSpan t = complete.Subtract(start); 
       long calculatedInterval = interval - t.Milliseconds < 0 ? 0 : interval - t.Milliseconds; 
       this.timer.Change(calculatedInterval, Timeout.Infinite); 
      } 
     }  
    } 
+3

感謝您的答案!問題出現在FileSystemWatcher的InternalBufferSize屬性中!默認情況下,它等於8192字節,而每個事件從它得到16個字節。我只是增加了這個屬性的價值!謝謝! – user1648361