C# 监控某一个文件的更改,并触发相关操作
2013-01-04 15:23
579 查看
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var watcher1 = new FileWatch(@"d:\data.txt");
watcher1.Start();
var watcher2 = new FileWatch(@"e:\123.txt");
watcher2.Start();
Console.Read();
}
}
public class FileWatch
{
private readonly FileSystemWatcher _fileWatcher;
private readonly HashSet<string> _hstbWatcher;
public FileWatch(string filePath)
{
_hstbWatcher = new HashSet<string>();
if (_fileWatcher == null)
{
var file = new FileInfo(filePath);
_fileWatcher = new FileSystemWatcher(file.DirectoryName) { Filter = file.Name, NotifyFilter = NotifyFilters.LastWrite };
_fileWatcher.Changed += _watcher_Changed;
}
}
public void Start()
{
_fileWatcher.EnableRaisingEvents = true;
}
public void Stop()
{
_fileWatcher.EnableRaisingEvents = false;
}
private void _watcher_Changed(object sender, FileSystemEventArgs e)
{
if (_hstbWatcher.Any(q => q.Equals(e.FullPath, StringComparison.CurrentCultureIgnoreCase)))
{
lock (_hstbWatcher)
{
_hstbWatcher.Remove(e.FullPath);
return;
}
}
lock (_hstbWatcher)
{
_hstbWatcher.Add(e.FullPath);
}
Console.WriteLine(e.FullPath + " " + e.ChangeType);
}
}
}
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var watcher1 = new FileWatch(@"d:\data.txt");
watcher1.Start();
var watcher2 = new FileWatch(@"e:\123.txt");
watcher2.Start();
Console.Read();
}
}
public class FileWatch
{
private readonly FileSystemWatcher _fileWatcher;
private readonly HashSet<string> _hstbWatcher;
public FileWatch(string filePath)
{
_hstbWatcher = new HashSet<string>();
if (_fileWatcher == null)
{
var file = new FileInfo(filePath);
_fileWatcher = new FileSystemWatcher(file.DirectoryName) { Filter = file.Name, NotifyFilter = NotifyFilters.LastWrite };
_fileWatcher.Changed += _watcher_Changed;
}
}
public void Start()
{
_fileWatcher.EnableRaisingEvents = true;
}
public void Stop()
{
_fileWatcher.EnableRaisingEvents = false;
}
private void _watcher_Changed(object sender, FileSystemEventArgs e)
{
if (_hstbWatcher.Any(q => q.Equals(e.FullPath, StringComparison.CurrentCultureIgnoreCase)))
{
lock (_hstbWatcher)
{
_hstbWatcher.Remove(e.FullPath);
return;
}
}
lock (_hstbWatcher)
{
_hstbWatcher.Add(e.FullPath);
}
Console.WriteLine(e.FullPath + " " + e.ChangeType);
}
}
}
相关文章推荐
- c# 实现2个程序同时操作读写一个文件、一个读一个写
- C# 文件流相关操作
- Krpano学习:在C#中修改全景场景属性(C#操作全景vtour.xml文件及相关瓦片数据/panos/*.tiles)
- C#文件读写及相关操作
- C#中文件相关操作
- 文件相关操作[C#]
- C# 文件相关操作
- C# 操作文件相关知识点
- C#常用文件相关操作
- C#文件操作常用相关类(Directory类、File类、Path类)
- rhel6文件系统属性更改相关操作
- [转]C#文件读写及相关操作
- 一个平凡菜鸟的C#琐碎总结 ----- 文件操作(二)
- C# 文件操作相关
- c# .Net :Excel NPOI导入导出操作教程之List集合的数据写到一个Excel文件并导出
- C#中执行批处理文件(.bat),执行数据库相关操作
- C#通过一个密码对文件进行加密解密操作
- C#文件、目录操作相关函数
- 【温故而知新:文件操作】C#的文件读写相关
- 黄聪:[C#]VS中如何设置相关的partial 类文件嵌套在一个文件下