FileSystemWatcher Question

K

Krish

Hello Gurus,

Pardon me for asking dumb question...

I wrote small csharp program to watch a folder for any created text file...
When i try to run through debugger and stop after "
watcher.EnableRaisingEvents = true;", i manually drag and drop windows text
file and this program doesnt seem to fire up... see code below and pl.
advise what wrong iam doing. Thanks.

public static void Main ()
{
Run();
}

public static void Run()
{
string FilePath = "D:\\BECSolution\\Jobs\\Faster\\bin\\Debug";
Console.WriteLine("File Monitoring Started");
Console.WriteLine("\t{0} is being monitored", FilePath);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = FilePath;
watcher.NotifyFilter = NotifyFilters.FileName |
NotifyFilters.CreationTime;
watcher.Filter = "*.txt";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}

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);
}
 
K

Kevin Spencer

You're creating your FileSystemWatcher class in function scope. When the
function exits, the FileSystemWatcher is no longer in scope; it is ready for
Garbage Collection. You need to declare it as a field in the class, and set
it up in the method. That way it will last for the lifetime of the class,
not the method.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 
K

Krish

Thank you for the reply.
Also adding a piece of following helped to catch files created

while( true )

{

ret = watcher.WaitForChanged(WatcherChangeTypes.Created);

}
 
K

Kevin Spencer

The problem with that method is that the method never exits. Unless you have
some other code in there that allows for an exit, the method will never
exit, and unless it is running in a separate thread, it will block all other
method calls, or any other work the class may want to do.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 

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