c# 监控本地文件夹,读取TXT文件 多线程
时间: 2023-10-28 19:22:33 浏览: 64
可以使用C#的FileSystemWatcher类来监控本地文件夹,然后使用多线程来读取TXT文件的内容。以下是一个简单的代码示例,演示如何使用FileSystemWatcher和多线程来实现此目标:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
class Program
{
static List<string> fileContents = new List<string>();
static void Main(string[] args)
{
string directoryPath = @"C:\example\";
FileSystemWatcher watcher = new FileSystemWatcher(directoryPath, "*.txt");
watcher.EnableRaisingEvents = true;
watcher.Created += OnCreated;
Console.WriteLine("Press 'q' to quit.");
while (Console.Read() != 'q') ;
}
private static void OnCreated(object sender, FileSystemEventArgs e)
{
Thread thread = new Thread(() =>
{
string[] lines = File.ReadAllLines(e.FullPath);
foreach (string line in lines)
{
fileContents.Add(line);
}
Console.WriteLine("File {0} has been read.", e.Name);
});
thread.Start();
}
}
```
在此示例中,我们首先创建了一个FileSystemWatcher对象来监控指定目录中的所有txt文件。然后,我们使用EnableRaisingEvents属性启用FileSystemWatcher对象的事件,然后订阅Created事件。当创建新的txt文件时,OnCreated方法将被调用,并在新的线程上读取txt文件的内容并将其存储在fileContents列表中。最后,我们打印一条消息,指示文件已被读取。
请注意,此示例中没有实现对fileContents列表的同步访问。如果多个线程同时访问列表,则可能会导致竞态条件和其他问题。要解决此问题,可以使用线程同步机制,如lock语句或Monitor类。