2012-09-05 72 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