C# FileSystemWatcher和未处理的文件
我使用FileSystemWatcher在网络目录中创建新文件时发出通知。我们处理文本文件(大约5KB大小),并在目录中创建新文件时立即删除它们。如果FileSystemWatcher windows服务因某种原因停止,我们必须在它恢复并运行后查找未处理的文件。在处理目录中的旧文件时,如何处理新文件的出现?有什么例子吗 谢谢, 下面是我使用简单表单的代码示例C# FileSystemWatcher和未处理的文件,c#,C#,我使用FileSystemWatcher在网络目录中创建新文件时发出通知。我们处理文本文件(大约5KB大小),并在目录中创建新文件时立即删除它们。如果FileSystemWatcher windows服务因某种原因停止,我们必须在它恢复并运行后查找未处理的文件。在处理目录中的旧文件时,如何处理新文件的出现?有什么例子吗 谢谢, 下面是我使用简单表单的代码示例 public partial class Form1 : Form { private System.IO.FileSystemW
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);
}
}
}当流程开始时,请执行以下操作:
- 首先获取文件夹的内容
- 处理每个文件(结束删除它们,就像现在一样)
- 重复此操作,直到文件夹中没有文件(再次选中此处,因为新文件可能已放置在文件夹中)
- 启动观察者