2017-02-16 46 views
0

我有一个文件夹被FileSystemWatcher服务监视,我用这个Answer来帮助我写入大文件。如何处理由FileSystemWatcher监视的文件夹中的快速连续文件创建?

但是,如果有连续的文件创建(100MB或更多),我会遇到问题。

问:我该如何解决这个问题?像大约10个文件(每个100MB)写入我的文件夹的示例。

注意:该文件夹通过我的网络访问。可能会创建文件,但不能完成/完成。 FileSystemWatcher可以在不完全写入的情况下处理文件。

检查,如果打开的文件抛出异常电流代码

private static bool IsFileLocked(FileInfo file) 
    { 
     FileStream stream = null; 
     try 
     { 
      stream = file.Open(FileMode.Open, 
        FileAccess.Read, FileShare.None); 
     } 
     catch (IOException) 
     { 
      //the file is unavailable because it is: 
      //still being written to 
      //or being processed by another thread 
      //or does not exist (has already been processed) 
      return true; 
     } 
     finally 
     { 
      if (stream != null) 
       stream.Close(); 
     } 

     //file is not locked 
     return false; 
    } 

当前代码检查是否有创建的文件。

private void FSWatcher_Created(object sender, System.IO.FileSystemEventArgs e) 
    { 
     var files = getFiles(FSWatcher.Path); //stores all filenames in the directory in a list 
     if (files.Count() > 0) 
     { 
      foreach (string file in files) 
      { 
       FileInfo file_info = new FileInfo(file); 
       while (IsFileLocked(file_info)) 
       { 
        Thread.Sleep(5000); //Sleep if file unavailable 
       } 
       //code to process the file 
      } 
      //some code here 
     } 
    } 

回答

0

我已经处理看在过去的文件夹的方式使用查询,而不是FileSystemWatcherits not 100% reliable anyway

我发过的所有文件循环的处理器,并试图将它们首先进入一个“处理”目录。如果文件写入完成,移动将(可能*)成功,因此一旦移动成功,移动的线程就可以安全地触发该文件的处理(例如在新线程中)。请注意,文件只能移动一次,这意味着您不会意外让两个不同的线程尝试同时处理文件。

*:它可能(但很少)的应用程序创建一个文件,可以移动,而其仍然打开

相关问题