FileSystemWatcher in Windows Service

G

Guest

I created a Windows Service (written in VB.NET) that uses a FileSystemWatcher
to monitor a directory for file creation. When files with a certain
extension are created in the directory, the file is opened and read
(something is done with the contents). Then the file is moved to a backup
directory. Everything works fine when the coe runs as a standard Windows app,
but when I run the code as a Windows Service, I get the following error when
I try to open the file:

The process cannot access the file "C:\Data\tests.txt" because it is being
used by another process.

Here is the VB code (FileSystemWatcher Created Event happens as it should):

....
Dim objFile As New FileInfo(fullPath)
Dim strContents As String
Dim objStream As StreamReader

' *** Error Happens on the next line ***
objStream = objFile.OpenText()

strContents = objStream.ReadToEnd()

' Close the stream
objStream.Close()


Thanks for any suggections.
 
A

Andrew Faust

Bill said:
I created a Windows Service (written in VB.NET) that uses a
FileSystemWatcher
to monitor a directory for file creation. When files with a
certain
extension are created in the directory, the file is opened and
read
(something is done with the contents). Then the file is moved
to a backup
directory. Everything works fine when the coe runs as a
standard Windows app,
but when I run the code as a Windows Service, I get the
following error when
I try to open the file:

The process cannot access the file "C:\Data\tests.txt" because
it is being
used by another process.

My first guess would be that your service is launching and trying
to work with the file before the process that put it there is
finished with it. When the file is put in the directory in the
first place, the process placing it there needs to be finished
and close the file, before your service will be allowed to
manipulate it.

Andrew Faust
 
G

Guest

If you want to detect whether the process that created the file has finished
writing to it (and closed it), you could periodically (in a loop, perhaps)
attempt to open it using something like:

Stream stream = null;
while (stream == null)
{
try
{
if (!File.Exists(path))
break;

stream = File.Open(path, FileMode.Open, FileAccess.Read,
FileShare.None);
}
catch (IOException)
{
Thread.Sleep(100);
}
}

That will cause your thread to pause until your application can gain
exclusive access to the file. You may want to add a time out etc.

Hope that helps.
 

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