using filewatcher to see if a file is available

M

Mo

Hi,

I have a windows service which is watching a directory and when a new
file is added it spawns a new thread and tries to read a file. In
order to check if the file is available for read I have the follwoing
code in the thread to check to see when the file is closed before it
open and reads the content. This is still locking up about 30% of the
time and the thread appears to time out. Does anybody have a good
method of checking if a file is available for read? here is what I
have in my thread to check for file availability

while (!FileAvailable)
{
try
{
fs = new System.IO.FileStream(SourceFilePath +
FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
FileAvailable = true;
}
catch
{
Thread.Sleep(10000);
FileAvailable = false;
}
}


Any suggestions is greatly appreciated.

Thanks,
Mo
..
 
P

Peter Duniho

Mo said:
Hi,

I have a windows service which is watching a directory and when a new
file is added it spawns a new thread and tries to read a file. In
order to check if the file is available for read I have the follwoing
code in the thread to check to see when the file is closed before it
open and reads the content. This is still locking up about 30% of the
time and the thread appears to time out.

What do you mean by "locking up" and "time out"? The thread doesn't
exit until the file is available, so maybe that's what you mean by
"locking up"? There's nothing in the thread that implements a "time
out" though. It just keeps trying until it succeeds.
Does anybody have a good
method of checking if a file is available for read?

The only truly reliable way to check to see if a file is available to
read is to try to read it, much as you're doing here. It's not clear to
me from reading your post what issue it is you're having though.
Assuming the file is eventually closed by the process that created it,
it seems to me that you should eventually successfully create a new
FileStream using the path of the file.

If that's not happening, then something unusual is going on. You should
be more specific about how the file is created, by what process, how
long you expect it take before that process finishes writing the file
and closes it, etc. What, exactly, is going wrong with the code you posted?

Pete
 

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

Similar Threads


Top