FileSystemWatcher does not raise events

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

To reporoduce, run the code.

Observed: Form is shown

Expected: message box should displayed.

How to fix ?

Andrus.

using System;
using System.Windows.Forms;
using System.IO;

class main {

[STAThreadAttribute()]

public static void Main() {
File.Delete("c:\\test");
using (FileSystemWatcher watch = new FileSystemWatcher()) {
watch.Path = "c:\\";
watch.Filter = "test";
watch.Created += new FileSystemEventHandler(OnChanged);
watch.Deleted += new FileSystemEventHandler(OnChanged);
watch.Changed += new FileSystemEventHandler(OnChanged);
watch.EnableRaisingEvents = true;
}
FileStream oFs = new FileStream("c:\\test", FileMode.CreateNew,
FileAccess.ReadWrite);
StreamWriter oWriter = new StreamWriter(oFs);
oWriter.Flush();
oWriter.Close();
oFs.Close();
File.Delete("c:\\test");
Application.Run(new Form());
}

static void OnChanged(object sender, FileSystemEventArgs e) {
MessageBox.Show(e.FullPath + e.ChangeType.ToString());
}
}
 
Andrus said:
To reporoduce, run the code.

Observed: Form is shown

Expected: message box should displayed.

How to fix ?

You've surrounded the use of "watch" with a using statement, so it's
being disposed immediately. It doesn't get a chance to actually do
anything.
 
1. First statement File.Delete ("C:\\test") will throw if the file doesn't
exist.
2. Filter should be a file specification so probably "*.*" should be used in
preference to "test".
3. Also your FileSystemWatcher is inside a using statement which means that
upon completion of the block the object will be deleted as the Dispose
method will be called... meaning that no events will be raised!

Move the code outside the using block to the inside of it.

- Andy
 
Andy Bates said:
1. First statement File.Delete ("C:\\test") will throw if the file doesn't
exist.

Nope - from the docs:

<quote>
Deletes the specified file. An exception is not thrown if the specified
file does not exist.
2. Filter should be a file specification so probably "*.*" should be used in
preference to "test".
3. Also your FileSystemWatcher is inside a using statement which means that
upon completion of the block the object will be deleted as the Dispose
method will be called... meaning that no events will be raised!

Move the code outside the using block to the inside of it.

Indeed, that's the problem.
 
Back
Top