C# FileSystemWatcher和未处理的文件

C# FileSystemWatcher和未处理的文件,c#,C#,我使用FileSystemWatcher在网络目录中创建新文件时发出通知。我们处理文本文件(大约5KB大小),并在目录中创建新文件时立即删除它们。如果FileSystemWatcher windows服务因某种原因停止,我们必须在它恢复并运行后查找未处理的文件。在处理目录中的旧文件时,如何处理新文件的出现?有什么例子吗 谢谢, 下面是我使用简单表单的代码示例 public partial class Form1 : Form { private System.IO.FileSystemW

我使用FileSystemWatcher在网络目录中创建新文件时发出通知。我们处理文本文件(大约5KB大小),并在目录中创建新文件时立即删除它们。如果FileSystemWatcher windows服务因某种原因停止,我们必须在它恢复并运行后查找未处理的文件。在处理目录中的旧文件时,如何处理新文件的出现?有什么例子吗

谢谢,

下面是我使用简单表单的代码示例

public partial class Form1 : Form
{
    private System.IO.FileSystemWatcher watcher;
    string tempDirectory = @"C:\test\";
    public Form1()
    {
        InitializeComponent();
        CreateWatcher();
        GetUnprocessedFiles();
    }
private void CreateWatcher()
{
    //Create a new FileSystemWatcher.
    watcher = new FileSystemWatcher();
    watcher.Filter = "*.txt";
    watcher.NotifyFilter = NotifyFilters.FileName;
      //Subscribe to the Created event.
    watcher.Created += new FileSystemEventHandler(watcher_FileCreated);
    watcher.Path = @"C:\test\";
    watcher.EnableRaisingEvents = true;
}

void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
    //Parse text file.
       FileInfo objFileInfo = new FileInfo(e.FullPath);
        if (!objFileInfo.Exists) return;  
        ParseMessage(e.FullPath);
}


  void ParseMessage(string filePath)
  {
       // Parse text file here 
  }

  void GetUnprocessedFiles()
  {
      // Put all txt files into array.
    string[] array1 = Directory.GetFiles(@"C:\test\"); 
    foreach (string name in array1)
    { 
        string path = string.Format("{0}{1}", tempDirectory, name)
        ParseMessage(path);
    }
  }

}当流程开始时,请执行以下操作:

  • 首先获取文件夹的内容
  • 处理每个文件(结束删除它们,就像现在一样)
  • 重复此操作,直到文件夹中没有文件(再次选中此处,因为新文件可能已放置在文件夹中)
  • 启动观察者

对于使用FileSystemWatcher的任何服务,我们总是在启动watcher之前首先处理目录中存在的所有文件。启动观察程序后,我们会启动一个计时器(间隔相当长),在不触发观察程序的情况下处理目录中出现的任何文件(这种情况时有发生)。这通常涵盖了所有的可能性。

谢谢您的回复。我考虑过了。虽然不太可能,但这不是一个好的解决方案。可以在上次文件检查和正在初始化的监视程序之间创建一个文件。