C#Help - FileSystemWatcher类

时间:2011-05-20 19:11:02

标签: c# .net windows

我有以下代码,虽然我想输出:

fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);

虽然我收到以下错误:

当前上下文中不存在名称“e”

我的代码如下:

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

namespace FileWatcherr
{
class Program
{    
    static void Main(string[] args)
    {
        string dirPath = "C:\\";
        FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath); 
        fileWatcher.IncludeSubdirectories = true;  
        fileWatcher.Filter = "*.exe";    
        // fileWatcher.Filter = "C:\\$Recycle.Bin";   
        //  fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);   
        fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);    
        //  fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);  
        //  fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);    
        fileWatcher.EnableRaisingEvents = true;      

        // updated code
        using(StreamWriter fileWriter = new StreamWriter("test2.txt"))
        {
            var data = true;
            fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);
        }

        Console.ReadKey(); 
    }



        static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine(e.OldName + " was renamed to " + e.Name);
        }

        static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.Name + " was deleted");
        }

        static void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("C:\\" + e.Name);
        }

        static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.Name + "");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

e是指事件方法的EventArgs参数。

如果你这样说:

using(StreamWriter fileWriter = new StreamWriter("test2.txt"))
    {
        var data = true;
        fileWriter.Write(e.OldName + " was renamed to " + e.Name + Environment.NewLine);
    }

中的

static void FileWatcher_Renamed(object sender, RenamedEventArgs e)

方法,它应该有用。

答案 1 :(得分:0)

从我在代码中看到的内容,您可以在main方法中获得Rename事件的代码,该代码不包含FileSystemEventArgs对象(称为“e。”)

我认为要解决此问题,您应该将“FileWatcher_Renamed”的主体更改为using块。