473,583 Members | 2,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(IOExcepti on)
{
goto ReadFile;
}
-------------------------------8<-------------------------

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

thanks,
Gabe
Nov 16 '05 #1
8 26705
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.co m

"Gabe Moothart" <ga**@imaginesy stems.net> wrote in message
news:OJ******** ******@TK2MSFTN GP09.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(IOExcepti on)
{
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.c om> wrote in
message news:eB******** *****@TK2MSFTNG P15.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.co m

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

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote
in message news:eB******** *****@TK2MSFTNG P15.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.c om> wrote in
message news:eQ******** ******@TK2MSFTN GP10.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.co m

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

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote
in message news:eQ******** ******@TK2MSFTN GP10.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.c om> wrote in
message news:uG******** ******@tk2msftn gp13.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
7308
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
8314
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: "Could Not Copy Temporary Files to the Output Directory" Error Message When You Build a Solution That Contains Multiple Projects I have tried all...
2
7761
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 foreach file in the files list and passed the file path to a function to read its content then process it then move it to another directory am reading...
2
7085
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 file using fileopen in VB.Net I am very sure that the file is not being used by any other process as I tried to open other files without success.Also...
4
27093
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 trying to do. The var logFileName is being passed into the function. Dim line as String Dim sr As New StreamReader(logFileName) 'It dies on this...
5
4706
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 attempts: OldName = "c:\albums\061203\email\DSC07272.JPG" NewName = "c:\albums\061203\email\Lalala.JPG"
8
8853
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. After I bounced IIS, then it worked fine. log4net.dll is in the Bin directory. What is going on here - this makes no sense to me.
0
2951
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 resuming for the file uploading if the client connection or server connection is down. E.g: Sunset.jpg (500KB) when i upload until half of it,...
3
3327
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 'E:\hshome\holsoftsystems\indusmotor.co.in\MTNMRN1\MTNMRN1\MTNMRN2\Hrm123.ldb' because it is being used by another process. the database is being used by another process. i have to zip this...
0
7888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7811
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8159
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8185
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6571
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3836
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2317
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1416
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.