Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using the below code to listen for change events of a file i download off a server and open. however the change event only gets fired the first time the file is saved, then on subsequent saves the file watcher does not fire the change events?

Can anyone see whats going on?

private FileSystemWatcher StartWatchingFile()
{
    fw = new FileSystemWatcher();
    fw.Path = this.directoryLocation;
    fw.Filter = this.Filename;

    fw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;

    // Add event handler
    fw.Changed += new FileSystemEventHandler(fw_Changed);

    // Open file        
System.Diagnostics.Process.Start(this.CreateAbsoluteFilePath(this.Filename));

    // Begin watching.
    fw.EnableRaisingEvents = true;

    return fw;
}

//************************  

    void fw_Changed(object sender, FileSystemEventArgs e)
    {
        MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
    }

EDIT: The StartWatchingFile() now returns the filewatcher which is kept in a class that will not be garbage collected, just to make sure i'm holding the whole class as thought the fw_changed() function might not be able to be called. So the whole class is now not getting garbage collectioned. The class is held in a ArrayList which is a public member of a class

Regards,

Jon

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
541 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is it reproduceable that it always works for the first time?

If not, the FileSystemWatcher might have been collected by the garbage collector in the meantime after StartWatchingFile has finished because it's declared locally.

If so, does the process you're starting probably lock the file so the file actually isn't modified?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...