C#怎么及时监控到其它程序占用的txt文件被改变
时间: 2023-11-27 09:51:02 浏览: 35
你可以使用FileSystemWatcher类来监视文件系统中的更改。FileSystemWatcher可以监视文件夹或文件,当它们被创建、删除、重命名或修改时,它会发出通知。以下是一个使用FileSystemWatcher监视txt文件更改的基本示例:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\example\directory";
watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press any key to stop monitoring...");
Console.ReadKey();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine("File {0} has been changed", e.Name);
}
}
```
在这个示例中,我们创建了一个FileSystemWatcher实例,并设置了其Path属性为要监视的文件夹路径。使用Filter属性设置要监视的文件类型。NotifyFilter属性设置要监视的更改类型,例如,我们只想监视文件的最后写入时间,则设置为NotifyFilters.LastWrite。
在OnChanged方法中,我们定义了当文件被更改时要执行的操作。在这个示例中,我们只是简单地打印出文件名,但你可以根据自己的需求进行操作。
最后,通过设置EnableRaisingEvents属性为true,FileSystemWatcher开始监视文件更改。当你想停止监视时,只需按下任意键即可停止程序。