FileSystemWatcher c#没有错误,无法正常工作

时间:2013-07-29 20:48:19

标签: c# filesystemwatcher

我不知道如何将我在c#上编写的代码与FileSystemWatcher类集成

    public static void watcherFunc()
    {
        FileSystemWatcher fileWatcher = new FileSystemWatcher(@"C:\Documents and Settings\Develop\Desktop\test\");
        fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
        fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
        fileWatcher.EnableRaisingEvents = true;
    }
    // Define the event handlers. 
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
    }

我试图在form1引导活动中调用它....我试着阅读如何做到这一点并且谷歌没有运气请帮助...谢谢!

1 个答案:

答案 0 :(得分:2)

据我所知,问题是当你完成方法时你的FileSystemWatcher超出了范围。因此,您不再活跃于捕捉事件。

尝试如下:

FileSystemWatcher fileWatcher = new FileSystemWatcher(@"C:\Documents and ettings\Develop\Desktop\test\");
public void Initialize() //initialization or Constructor
{
    fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
    fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
    fileWatcher.EnableRaisingEvents = true;
}

// Define the event handlers. 
private void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
    MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}

如果需要,请参阅FileWatcher Tutorial获取更多帮助