0

我写了一个小应用程序来监控文件的变化。当我运行它时,每次我得到关于路径的异常。我不明白为什么。路径是真实存在的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
        }

        public static void Run()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"D:\test\1.txt";
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            watcher.Changed +=new FileSystemEventHandler(watcher_Changed);
            watcher.EnableRaisingEvents = true;
        }

static void  watcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine(e.ChangeType);
}


    }
}
4

1 回答 1

1

FileSystemWatcher.Path 应该是 Path 而不是文件名

watcher.Path = @"D:\test"; 
watcher.Filter = "1.txt";

private static void watcher_Changed(object source, FileSystemEventArgs e)
{
    // this test is unnecessary if you plan to monitor only this file and
    // have used the proper constructor or the filter property
    if(e.Name == "1.txt")
    {
         WatcherChangeTypes wct = e.ChangeType;
         Console.WriteLine("File {0} {1}", e.FullPath, wct.ToString());
    }
}

您还可以使用带有两个参数(路径和文件过滤器)的构造函数来限制监视。

FileSystemWatcher watcher = new FileSystemWatcher(@"d:\test", "1.txt");  

请参阅 MSDN 参考资料

于 2012-08-30T10:10:59.797 回答