你这个是想文件发生改变时,自动调用一个函数,做出一些操作呢。
还是有一个按钮(或者别的什么),你去点击一下,然后检测下一个文件,是否发生了变化?
下面的代码,监控d盘下的所有.txt文件的修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
static
void
TestFileSystemWatcher()
{
FileSystemWatcher watcher =
new
FileSystemWatcher();
try
{
watcher.Path =
@"d:\Test"
;
}
catch
(ArgumentException e)
{
Console.WriteLine(e.Message);
return
;
}
//设置监视文件的哪些修改行为
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter =
"*.txt"
;
watcher.Changed +=
new
FileSystemEventHandler(OnChanged);
watcher.Created +=
new
FileSystemEventHandler(OnChanged);
watcher.Deleted +=
new
FileSystemEventHandler(OnChanged);
watcher.Renamed +=
new
RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents =
true
;
Console.WriteLine(
@"Press 'q' to quit app."
);
while
(Console.Read() !=
'q'
);
}
static
void
OnChanged(
object
source, FileSystemEventArgs e)
{
Console.WriteLine(
"File:{0} {1}!"
, e.FullPath, e.ChangeType);
}
static
void
OnRenamed(
object
source, RenamedEventArgs e)
{
Console.WriteLine(
"File:{0} renamed to\n{1}"
, e.OldFullPath, e.FullPath);
}
|