473,320 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

determine if file is being used by another process

Hi,
I'm writing a windows service which interacts with a separate process.
Basically, it calls a process which creates a file, and then my service
reads that file. The problem is, the external process can take a second
or two to finish writing the file. If I try to read the file to soon, I
get an exception that "The process cannot access the file because it is
being used by another process".

I could just set a timer, but the time it takes the external process to
create the file is highly variable, and I'd rather not wait longer than
I have to. What I'd like to do is run a loop that constantly checks the
status of that file (basically a "busy waiting" loop) and only allows
the File.OpenRead() when it can succeed. Right now I'm using this
monstrosity:

-------------------------------8<-------------------------
FileStream fs;
ReadFile:
try
{
fs = File.OpenRead("TestFile.txt");
}
catch(IOException)
{
goto ReadFile;
}
-------------------------------8<-------------------------

But there has to be a better way. Any suggestions?

thanks,
Gabe
Nov 16 '05 #1
8 26676
Gabe,

Instead of doing that, I would recommend declaring the CreateFile API
function so that you can call it through the P/Invoke layer. The CreateFile
function will return an error code if you can not access the file, which is
much cleaner than handling the exception.

Once you have that, if you are able to open the file with the CreateFile
API, then you can pass the handle to the FileStream constructor, which takes
a file handle.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Gabe Moothart" <ga**@imaginesystems.net> wrote in message
news:OJ**************@TK2MSFTNGP09.phx.gbl...
Hi,
I'm writing a windows service which interacts with a separate process.
Basically, it calls a process which creates a file, and then my service
reads that file. The problem is, the external process can take a second or
two to finish writing the file. If I try to read the file to soon, I get
an exception that "The process cannot access the file because it is being
used by another process".

I could just set a timer, but the time it takes the external process to
create the file is highly variable, and I'd rather not wait longer than I
have to. What I'd like to do is run a loop that constantly checks the
status of that file (basically a "busy waiting" loop) and only allows the
File.OpenRead() when it can succeed. Right now I'm using this monstrosity:

-------------------------------8<-------------------------
FileStream fs;
ReadFile:
try
{
fs = File.OpenRead("TestFile.txt");
}
catch(IOException)
{
goto ReadFile;
}
-------------------------------8<-------------------------

But there has to be a better way. Any suggestions?

thanks,
Gabe

Nov 16 '05 #2
Nicholas,
Thanks, that's just what I needed.

Gabe
Gabe,

Instead of doing that, I would recommend declaring the CreateFile API
function so that you can call it through the P/Invoke layer. The CreateFile
function will return an error code if you can not access the file, which is
much cleaner than handling the exception.

Once you have that, if you are able to open the file with the CreateFile
API, then you can pass the handle to the FileStream constructor, which takes
a file handle.

Hope this helps.

Nov 16 '05 #3

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eB*************@TK2MSFTNGP15.phx.gbl...
Gabe,

Instead of doing that, I would recommend declaring the CreateFile API
function so that you can call it through the P/Invoke layer. The
CreateFile function will return an error code if you can not access the
file, which is much cleaner than handling the exception.

Once you have that, if you are able to open the file with the
CreateFile API, then you can pass the handle to the FileStream
constructor, which takes a file handle.

Hope this helps.


Sorry to ask, but why do you thing it's much cleaner to PInvoke instead of
handling the exception?
You have to test the return value of CreateFile, and only retry the call if
the file is in use, but you have to test for other error conditions too and
take appropriate actions (throw or ..). IMO when all is done (correctly )you
will have coded a great deal of what's been done in File.OpenRead.

Note also that v2's FileStream constructors that accept an IntPtr as handle
are deprecated, so you will have to encapsulate the handle returned in a
SafeHandle before passing to the FileStream ctor.
Willy.

Nov 16 '05 #4
Willy,

The OP is trying to handle business logic depending on whether or not
the file is in use. When coding business logic, flow control, IMO, should
never be predicated on exception handling, especially when there is a way to
check the status.

Of course, this is a matter of preference. If other people want to base
their logic on exception handling, they are free to do so, but I think there
is a strong camp that disagrees with this approach.

Also, the OP specifically asked for a solution that did not involve
using exceptions to determine if the file was in use.

From a performance standpoint, I think that the seven or so extra
instructions to call API through the P/Invoke layer (which are going to be
called anyways by the constructor if you didn't pass in a file handle) are a
small price to pay as opposed to throwing an exception.

You are right about the constructor being marked as obsolete and passing
a SafeHandle. I didn't mention it because I assume that most people are not
using the beta, but the OP should know that as well.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Willy Denoyette [MVP]" <wi*************@pandora.be> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:eB*************@TK2MSFTNGP15.phx.gbl...
Gabe,

Instead of doing that, I would recommend declaring the CreateFile API
function so that you can call it through the P/Invoke layer. The
CreateFile function will return an error code if you can not access the
file, which is much cleaner than handling the exception.

Once you have that, if you are able to open the file with the
CreateFile API, then you can pass the handle to the FileStream
constructor, which takes a file handle.

Hope this helps.


Sorry to ask, but why do you thing it's much cleaner to PInvoke instead of
handling the exception?
You have to test the return value of CreateFile, and only retry the call
if the file is in use, but you have to test for other error conditions too
and take appropriate actions (throw or ..). IMO when all is done
(correctly )you will have coded a great deal of what's been done in
File.OpenRead.

Note also that v2's FileStream constructors that accept an IntPtr as
handle are deprecated, so you will have to encapsulate the handle returned
in a SafeHandle before passing to the FileStream ctor.
Willy.

Nov 16 '05 #5

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eQ**************@TK2MSFTNGP10.phx.gbl...
Willy,

The OP is trying to handle business logic depending on whether or not
the file is in use. When coding business logic, flow control, IMO, should
never be predicated on exception handling, especially when there is a way
to check the status.

Of course, this is a matter of preference. If other people want to
base their logic on exception handling, they are free to do so, but I
think there is a strong camp that disagrees with this approach.

Also, the OP specifically asked for a solution that did not involve
using exceptions to determine if the file was in use.

From a performance standpoint, I think that the seven or so extra
instructions to call API through the P/Invoke layer (which are going to be
called anyways by the constructor if you didn't pass in a file handle) are
a small price to pay as opposed to throwing an exception.

You are right about the constructor being marked as obsolete and
passing a SafeHandle. I didn't mention it because I assume that most
people are not using the beta, but the OP should know that as well.


Nicholas,

I'm not talking about the performance differences between both, I'm talking
about the extra lines of code that are needed to make it more robust,
especially in the case of a windows service.
And IMO it's pretty wrong to loop on CreateFile calls [without any sleep in
between (pun intended) - see later] and only terminate the loop when the
status is OK. What if the status is something like "access denied or file
does not exist or wrong open mode" you will have to exit the loop and take
an action don't you think so?
Now whiter you handle exceptions or error codes, you should never call an
API like CreateFile is a closed loop without some sleep in between the
calls.
If you average file creation time is something like 1 sec., put a sleep of
0.5 - 1 sec. in between the calls, handle the exception or the error return
and retry when still busy. That way you will only throw a very few times per
file you process. However, if you keep your closed loop your thread will
consume most if not all CPU resources and disturb the external process in
such a way that it can dramatically increase the file creation time when run
on a single CPU box.

Willy.

Nov 16 '05 #6
Willy,

The problem you describe will exist in both cases, and the solution
would be the same in both cases. Basically, the thread should be put to
sleep in between checks. Whether or not the OP uses exceptions to determine
the cause of the error, or the result from CreateFile, the need to put the
thread to sleep in that loop is still needed.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Willy Denoyette [MVP]" <wi*************@pandora.be> wrote in message
news:er*************@TK2MSFTNGP14.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:eQ**************@TK2MSFTNGP10.phx.gbl...
Willy,

The OP is trying to handle business logic depending on whether or not
the file is in use. When coding business logic, flow control, IMO,
should never be predicated on exception handling, especially when there
is a way to check the status.

Of course, this is a matter of preference. If other people want to
base their logic on exception handling, they are free to do so, but I
think there is a strong camp that disagrees with this approach.

Also, the OP specifically asked for a solution that did not involve
using exceptions to determine if the file was in use.

From a performance standpoint, I think that the seven or so extra
instructions to call API through the P/Invoke layer (which are going to
be called anyways by the constructor if you didn't pass in a file handle)
are a small price to pay as opposed to throwing an exception.

You are right about the constructor being marked as obsolete and
passing a SafeHandle. I didn't mention it because I assume that most
people are not using the beta, but the OP should know that as well.


Nicholas,

I'm not talking about the performance differences between both, I'm
talking about the extra lines of code that are needed to make it more
robust, especially in the case of a windows service.
And IMO it's pretty wrong to loop on CreateFile calls [without any sleep
in between (pun intended) - see later] and only terminate the loop when
the status is OK. What if the status is something like "access denied or
file does not exist or wrong open mode" you will have to exit the loop and
take an action don't you think so?
Now whiter you handle exceptions or error codes, you should never call an
API like CreateFile is a closed loop without some sleep in between the
calls.
If you average file creation time is something like 1 sec., put a sleep of
0.5 - 1 sec. in between the calls, handle the exception or the error
return and retry when still busy. That way you will only throw a very few
times per file you process. However, if you keep your closed loop your
thread will consume most if not all CPU resources and disturb the external
process in such a way that it can dramatically increase the file creation
time when run on a single CPU box.

Willy.

Nov 16 '05 #7


"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uG**************@tk2msftngp13.phx.gbl...
Willy,

The problem you describe will exist in both cases, and the solution
would be the same in both cases. Basically, the thread should be put to
sleep in between checks. Whether or not the OP uses exceptions to
determine the cause of the error, or the result from CreateFile, the need
to put the thread to sleep in that loop is still needed.
--


Nicholas,

Agreed, and that's exactly why I prefer to use the FCL and handle the
exceptions, I don't need to declare the PInvoke (maintenance issue!!) stuff
and other extra code, it's already there in the framework, the exception
overhead is IMO a non issue.

Willy.
Nov 16 '05 #8
I agree with Willy. There is just too much overhead for nothing in
using the CreateFile API call. I, personally, think that exception
handling is a better way of doing it.

Nov 16 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Pekka Niiranen | last post by:
Hi, I have used the following example from win32 extensions: -----SCRIPT STARTS---- import win32file import win32con import win32security import pywintypes
4
by: Mountain Bikn' Guy | last post by:
I am having serious problems with the following IDE bug: Could not write to output file 'x.dll' -- 'The process cannot access the file because it is being used by another process. ' and BUG:...
2
by: Raed Sawalha | last post by:
Hello , I have windows service which do listening to specified directory using FileSystemWatcher , on Created Event and Get all the files in the directory using Directory.GetFiles function then...
2
by: Piyush | last post by:
Hi, I am getting the error "The process cannot access the file "C:\Documents and Settings\piyush\Desktop\200309181051.ktl" because it is being used by another process." when I try to open this...
4
by: funkmusha | last post by:
I am trying to read a log file using vb.net. I get an error stating "The process cannot access the file 'C:\test.log' because it is being used by another process." Below is a sample of what I am...
5
by: bulldog8 | last post by:
I've read numerous posts and have tried multiple approaches that I found, but just cannot get a file renamed. I am using VB.Net 2002 ... Here is what I have tried: 1) Code common to all...
8
by: =?Utf-8?B?RGF2aWQgVGhpZWxlbg==?= | last post by:
Hi; I copied a new set of files over to my ASP.NET dir (and subdirs) on our test server. This replaced every file for the app. When I first then tried to bring it up, I got the below error. ...
0
nightangel
by: nightangel | last post by:
Hi dude,what i was done in my application is uploading a image file to my server using FTP, it work great when pushing a file into the server path using FTP. The problem i met now is i need to do a...
3
by: gracepaul | last post by:
hi, i got an exception while i m trying to zip/unzip a database inside the serverfolder System.IO.IOException: The process cannot access the file...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.