FileSystemWatcher does not raise events

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());
}
}
 
J

Jon Skeet [C# MVP]

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.
 
A

Andy Bates

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
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top