M
Marek
Hello.
I'm using FileSystemWatcher to monitor creation of files
in specified directory and its subdirectories:
dirWorks = new DirectoryWorks (strDirName);
FileSystemWatcher watcher = new FileSystemWatcher
(strDirName);
watcher.IncludeSubdirectories = true;
watcher.Created += new FileSystemEventHandler
(dirWorks.OnCreated);
watcher.EnableRaisingEvents = true;
In the OnCreated event handler, I need to open the
created file and read from it:
public void OnCreated (object sender, FileSystemEventArgs
e)
{
...
try
{
file = new FileInfo (e.FullPath);
fstream = file.Open (FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite);
stream = new StreamReader (fstream);
for (string line = stream.ReadLine (); line != null;
line = stream.ReadLine ())
{
Console.WriteLine (line);
}
}
catch (Exception ex)
{
...
}
...
}
But I often (not always) get this exception:
Unhandled Exception: System.IO.IOException: The process
cannot access the file "5\msg002.txt" because it is being
used by another process.
Why? The only way I can block this exception is to sleep
this thread [I put this code at the beginning of
OnCreated event handler]:
Thread.Sleep (1000);
Why this prevents the exception to occur?
Thanks for help!
Marek
I'm using FileSystemWatcher to monitor creation of files
in specified directory and its subdirectories:
dirWorks = new DirectoryWorks (strDirName);
FileSystemWatcher watcher = new FileSystemWatcher
(strDirName);
watcher.IncludeSubdirectories = true;
watcher.Created += new FileSystemEventHandler
(dirWorks.OnCreated);
watcher.EnableRaisingEvents = true;
In the OnCreated event handler, I need to open the
created file and read from it:
public void OnCreated (object sender, FileSystemEventArgs
e)
{
...
try
{
file = new FileInfo (e.FullPath);
fstream = file.Open (FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite);
stream = new StreamReader (fstream);
for (string line = stream.ReadLine (); line != null;
line = stream.ReadLine ())
{
Console.WriteLine (line);
}
}
catch (Exception ex)
{
...
}
...
}
But I often (not always) get this exception:
Unhandled Exception: System.IO.IOException: The process
cannot access the file "5\msg002.txt" because it is being
used by another process.
Why? The only way I can block this exception is to sleep
this thread [I put this code at the beginning of
OnCreated event handler]:
Thread.Sleep (1000);
Why this prevents the exception to occur?
Thanks for help!
Marek