Search code examples
c#eventsxml-serializationfilesystemwatcher

FileSystemWatcher didnt invoke change event


I wrote the following code.

 [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();



    }
}

now I thought that after the following line OnChanged event will invoked but no...

x.Serialize(fs, m);

also after this line nothing happened

fs.Close();

any idea?


Solution

  • You must set EnableRaisingEvents to true in order to start raising events.