Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

c# - FileSystemWatcher - only the change event once firing once?

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...