Monday, March 26, 2012

trouble getting FileSystemWatcher to work

I am doing an example in my MSPress MCTS 70-536 book which uses FileSystemWatcher to see if a file is created or deleted in a directory.

However, it doesn't work since it is a console application and the program ends i.e. stops monitoring events, so it can never respond to an added/deleted file.

I tried to put it in an endless loop that it didn't work, either, never noticed a created file.

What am I missing?

How can I get FileSystemWatcher to work in a console application? Is it possible, the book seems to think so.

Thanks,

1class Program2 {3static void Main(string[] args)4 {56 FileSystemWatcher watcher =new FileSystemWatcher();7 watcher.Path = @dotnet.itags.org."c:\";89//register10 watcher.Created +=new FileSystemEventHandler(watcher_Changed);11 watcher.Deleted +=new FileSystemEventHandler(watcher_Changed);1213//start14 watcher.EnableRaisingEvents =true;1516 }1718static void watcher_Changed(object sender, FileSystemEventArgs e)19 {20 Console.WriteLine("here");21 }22 }

Hi Aubrey,

I'm guessing you were probably having trouble because the application you created was using a "busy" loop which effectively blocked the ability of other threads to execute. I was able to get good results by using a loop at the end of Main() that contained a long call to Thread.Sleep(), like this:

while (true)
{
System.Threading.Thread.Sleep(60000);
}

HTH,
Clay


can u explain the use of File system watcher. I wanted to know more about it

thanks

vikram

Vikram's Blog

0 comments:

Post a Comment