【问题标题】:FileSystemWatcher didnt invoke change eventFileSystemWatcher 没有调用更改事件
【发布时间】:2012-04-12 00:02:32
【问题描述】:

我写了以下代码。

 [XmlRoot("myxml")]
public class myxml
{
    [XmlElement("one")]
    public string one { get; set; }
    [XmlElement("two")]
    public string two { get; set; }
}
class Program
{
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
    }

  // 

    static void Main(string[] args)
    {
        myxml m = new myxml();
        m.one = "111";
        m.two = "222";
        FileSystemWatcher watcher = new FileSystemWatcher(@"c:\", "myxml.xml");
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        FileStream fs = new FileStream(@"c:\myxml.xml", FileMode.Open);
        XmlSerializer x = new XmlSerializer(m.GetType());
        x.Serialize(fs, m);
        fs.Close();



    }
}

现在我认为在以下行之后 OnChanged 事件将被调用但没有......

x.Serialize(fs, m);

在这一行之后也没有发生任何事情

fs.Close();

有什么想法吗?

【问题讨论】:

    标签: c# events xml-serialization filesystemwatcher


    【解决方案1】:

    您必须将 EnableRaisingEvents 设置为 true 才能开始引发事件。

    【讨论】:

    • 谢谢,女巫线后会升吗?在x.Serialize(fs, m);fs.Close(); 之后
    • 我不知道 Serialize 是否会刷新 IO 缓冲区,但 Close 肯定会这样做。但是,使用您的程序绝对有可能,我认为很可能没有打印任何内容,因为观察者没有机会触发事件,程序在调用 Close 后终止。
    • 它只是测试应用程序来查看它是否引发事件,我只需要确保只有在我完成序列化文件后才会引发 onChange 事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多