473,399 Members | 2,159 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,399 software developers and data experts.

Check for file in use

Is there an easy way to check to see if a file is in use?

I want to open a CSV file from my .NET2 program, and write to it. However,
the file could be in use by another program. If that is the case, I don't
want to attempt to write to it, just abort.

Thanks,
Brian
Aug 15 '07 #1
15 3037
Brian,

You could use the FileStream class and try to open the file with the
sharing/read/write options you need, and then catch the IOException (I
believe) that is thrown. However, an exception of this type can be thrown
for other conditions (like a disk error) and it's not clear (aside from the
message, which you can't reliably code against) from that exception what the
IO condition is.

Instead, what you can do is call the CreateFile API function through the
P/Invoke layer. If it returns a value of INVALID_HANDLE_VALUE, then you can
call the static GetLastWin32Error on the Marshal class and get the value
from GetLastError. This should correspond specifically to a value in
winerror.h which indicates that the file is currently in use.

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

"Brian Simmons" <ce******@newsgroup.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Is there an easy way to check to see if a file is in use?

I want to open a CSV file from my .NET2 program, and write to it.
However, the file could be in use by another program. If that is the
case, I don't want to attempt to write to it, just abort.

Thanks,
Brian

Aug 15 '07 #2
Hello, Brian!

Put the code that opens the file into try/catch(IOException) block. In the
catch
handle assume that file is in use. You can also check IOExceptio:HResult
property as it may contain
Win32 error number that corresponds to "File is in use by another process"

Also have a look at http://www.thescripts.com/forum/thread251072.html
You wrote on Wed, 15 Aug 2007 10:59:28 -0400:

BSI want to open a CSV file from my .NET2 program, and write to it.
BSHowever, the file could be in use by another program. If that is the
BScase, I don't want to attempt to write to it, just abort.
With best regards, Vadym Stetsiak.
Blog: http://vadmyst.blogspot.com
Aug 15 '07 #3
The OP can't check the HResult property because it is protected. The OP
would have to use reflection, which is a little bit too much overhead, IMO.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Vadym Stetsiak" <va*****@gmail.comwrote in message
news:u3**************@TK2MSFTNGP04.phx.gbl...
Hello, Brian!

Put the code that opens the file into try/catch(IOException) block. In the
catch
handle assume that file is in use. You can also check IOExceptio:HResult
property as it may contain
Win32 error number that corresponds to "File is in use by another process"

Also have a look at http://www.thescripts.com/forum/thread251072.html
You wrote on Wed, 15 Aug 2007 10:59:28 -0400:

BSI want to open a CSV file from my .NET2 program, and write to it.
BSHowever, the file could be in use by another program. If that is the
BScase, I don't want to attempt to write to it, just abort.
With best regards, Vadym Stetsiak.
Blog: http://vadmyst.blogspot.com

Aug 15 '07 #4
Nicolas, good answer, when i look on this quiz, i think lets try to delete
it, in case of exception so, the file is being used.

A JOKE.
--
Sincerely
Yaron Karni
http://dotnetbible.blogspot.com/
"Nicholas Paldino [.NET/C# MVP]" wrote:
Brian,

You could use the FileStream class and try to open the file with the
sharing/read/write options you need, and then catch the IOException (I
believe) that is thrown. However, an exception of this type can be thrown
for other conditions (like a disk error) and it's not clear (aside from the
message, which you can't reliably code against) from that exception what the
IO condition is.

Instead, what you can do is call the CreateFile API function through the
P/Invoke layer. If it returns a value of INVALID_HANDLE_VALUE, then you can
call the static GetLastWin32Error on the Marshal class and get the value
from GetLastError. This should correspond specifically to a value in
winerror.h which indicates that the file is currently in use.

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

"Brian Simmons" <ce******@newsgroup.nospamwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Is there an easy way to check to see if a file is in use?

I want to open a CSV file from my .NET2 program, and write to it.
However, the file could be in use by another program. If that is the
case, I don't want to attempt to write to it, just abort.

Thanks,
Brian


Aug 15 '07 #5
Nicholas Paldino [.NET/C# MVP] wrote:
The OP can't check the HResult property because it is protected. The OP
would have to use reflection, which is a little bit too much overhead, IMO.
And using p/invoke to call CreateFile directly isn't?

IMHO, the real answer is to just catch the exception and report it to
the user if it occurs. Yes, other exceptions could occur. But they
will have unique Message properties that can be displayed to the user,
and any exception needs to be dealt with, not just the one involving a
file that's already in use.

Yes, it's difficult for the code to do something conditionally based on
the exact error, but IMHO it's not necessary for the code to do that.
Any error that prevents the file from being opened is a problem.

Pete
Aug 15 '07 #6
"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:13*************@corp.supernews.com...
Nicholas Paldino [.NET/C# MVP] wrote:
> The OP can't check the HResult property because it is protected. The
OP would have to use reflection, which is a little bit too much overhead,
IMO.

And using p/invoke to call CreateFile directly isn't?
Obviously, IMO, it's not.
IMHO, the real answer is to just catch the exception and report it to the
user if it occurs. Yes, other exceptions could occur. But they will have
unique Message properties that can be displayed to the user, and any
exception needs to be dealt with, not just the one involving a file that's
already in use.
I disagree here. The OP explicitly stated that they wanted to abort the
operation. Whether or not the OP wants it to abort silently, or not
silently was not specified.

If the OP wants the program to abort silently, then I would say just let
the exception fly and then wrap all the code in a try/catch statement, doing
nothing in the catch statement.

If the OP wants the program to not abort silently, then I whether or not
to propogate the exception would depend on how user-friendly the OP wants to
make his program. If the OP doesn't want something that is completely
user-friendly, then just let the exceptions fly.

However, if the does want something more user friendly message based on
a specific condition that can be checked for (in this case, is the file in
use), then working with IOException is not viable here, as it doesn't expose
the information in a way that can be easily ascertained.

The OP ^could^ use the suggestion to use the HResult property, but it
would require reflection, and at that point, you are basing the logic on an
implementation detail, which I think we would agree is a bad thing.

That leaves checking for the condition before trying to access the file,
which leaves the call to CreateFile.
Yes, it's difficult for the code to do something conditionally based on
the exact error, but IMHO it's not necessary for the code to do that. Any
error that prevents the file from being opened is a problem.
Well, whether or not it's a problem, that's for the OP (and the users of
his program) to decide, really. If he could clarify it more, that would
help.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
Aug 15 '07 #7
There's always the remote possibility that the file won't be shared the
moment he checks it but will then be shared the moment he tries to open it
for (exclusive) writing. He therefore has to deal with the exception anyway.
Why waste the effort up front. I would personally consider a (reusable)
wrapper function that opens the file, catches the "IOException" and then
checks if it's really a sharing violation (which might also be gone by this
point so you can't entirely escape the problem - a "NumberOfRetries"
mechanism would usually solve thits however). If a sharing violation is
detected then simply throw a (custom) "SharingViolationException" with the
original "IOException" as its inner exception.
Aug 15 '07 #8
Larry,

That's the thing, how do you detect that the IOException actually occurs
as the result of the file being open? The two options are to use reflection
to get the HResult property which is protected and then check the error
code, or to parse the Message text, which is fragile at best (because of the
possibility of the Message property changing due to updates in the framework
and because of localization issues as well, as the Message property is more
than likely going to be localized). Neither is particularly stable, as they
both depend on implementation details.

Looking at the Marshal class, I realize that you could call the static
GetHRForException method to get the HRESULT code of the exception. This
HRESULT is the result of calling the HRESULT_FROM_WIN32 macro on the error
code ERROR_SHARING_VIOLATION (which has a value of 32):

http://msdn2.microsoft.com/en-us/library/ms680746.aspx

Looking in the code by calling the GetHRForException method, you can see
that the value 32 is definitely there (you have to convert to an unsigned
integer). Unfortunately, there is no definite way to map an HRESULT back to
a Win32 error code, as described here:

http://blogs.msdn.com/oldnewthing/ar...03/942851.aspx

I would say checking the IOException instance in this way is slightly
better, as you are still depending on an implementation detail (in the
conversion from the HRESULT to the Win32 error code). Granted, it's highly
unlikely that you are going to get an IOException which has an error code in
the HRESULT which is from a different facility or of a different severity,
so in the end, it's up to you what your poison is.

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

"Larry Smith" <no_spam@_nospam.comwrote in message
news:%2******************@TK2MSFTNGP06.phx.gbl...
There's always the remote possibility that the file won't be shared the
moment he checks it but will then be shared the moment he tries to open it
for (exclusive) writing. He therefore has to deal with the exception
anyway. Why waste the effort up front. I would personally consider a
(reusable) wrapper function that opens the file, catches the "IOException"
and then checks if it's really a sharing violation (which might also be
gone by this point so you can't entirely escape the problem - a
"NumberOfRetries" mechanism would usually solve thits however). If a
sharing violation is detected then simply throw a (custom)
"SharingViolationException" with the original "IOException" as its inner
exception.

Aug 15 '07 #9
That's the thing, how do you detect that the IOException actually
occurs as the result of the file being open? The two options are to use
reflection to get the HResult property which is protected and then check
the error code, or to parse the Message text, which is fragile at best
(because of the possibility of the Message property changing due to
updates in the framework and because of localization issues as well, as
the Message property is more than likely going to be localized). Neither
is particularly stable, as they both depend on implementation details.

Looking at the Marshal class, I realize that you could call the static
GetHRForException method to get the HRESULT code of the exception. This
HRESULT is the result of calling the HRESULT_FROM_WIN32 macro on the error
code ERROR_SHARING_VIOLATION (which has a value of 32):

http://msdn2.microsoft.com/en-us/library/ms680746.aspx

Looking in the code by calling the GetHRForException method, you can
see that the value 32 is definitely there (you have to convert to an
unsigned integer). Unfortunately, there is no definite way to map an
HRESULT back to a Win32 error code, as described here:

http://blogs.msdn.com/oldnewthing/ar...03/942851.aspx

I would say checking the IOException instance in this way is slightly
better, as you are still depending on an implementation detail (in the
conversion from the HRESULT to the Win32 error code). Granted, it's
highly unlikely that you are going to get an IOException which has an
error code in the HRESULT which is from a different facility or of a
different severity, so in the end, it's up to you what your poison is.
In practice the situation doesn't normally require this level of precision.
If an "IOException" occurs and the equivalent Win32 function then indicates
a sharing violation only milliseconds later, you're pretty much guaranteed
that's what the problem is. The odds of the "IOException" being something
else are incredibly remote. Let's say it is however. Well there's still a
sharing violation at the Win32 level so reporting that is still accurate.
It's really (almost) as if you relied on Win32 directly in the first place
(for all intents and purposes). Since the course of action at this point for
most programs is to inform the user and/or log the error, you can simply
report something like:

Unable to open file "YourFile" due to a sharing violation. See application
event log for further details.

You can then clarify the situation in the log by dumping the original
"IOException" in addition to the sharing violation itself. While not a
perfect course of action theoretically, in reality it will work just fine.
In any case, I do agree with your HRESULT assessment. Not only is it an
implementation detail that you shouldn't rely on (since there's no guarantee
that ERROR_SHARING_VIOLATION will be propagated back), it seems implausible
to me that MSFT would ever recommend using "GetHRForException()" for this
purpose (mapping a standard .NET exception to a corresponding Win32 error -
in theory .NET has nothing to do with Win32).
Aug 16 '07 #10
Hi Brian,

When a .CSV file is opened by Excel or other programs except Notepad, it is
opened exclusively. We could make us of this feature to check if the file
is in use. That is, try to open this file to see if there's an exception.
If yes, this file is in use; otherwise, it's not in use.

The following is a sample.

public bool IsInUse(string filename)
{
try
{
System.IO.FileStream fs =
System.IO.File.OpenWrite(filename)
fs.Close();
return false;
}
catch (Exception exp)
{
return true;
}
}

Hope this helps.
If you have any question, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 16 '07 #11
Linda Liu [MSFT] wrote:
Hi Brian,

When a .CSV file is opened by Excel or other programs except Notepad, it is
opened exclusively. We could make us of this feature to check if the file
is in use. That is, try to open this file to see if there's an exception.
If yes, this file is in use; otherwise, it's not in use.

The following is a sample.

public bool IsInUse(string filename)
{
try
{
System.IO.FileStream fs =
System.IO.File.OpenWrite(filename)
fs.Close();
return false;
}
catch (Exception exp)
{
return true;
}
}

Hope this helps.
If you have any question, please feel free to let me know.
Linda, how can you possibly assume that the only exception that may
occur in the code in the try block would be from a sharing violation?

Never, ever catch an Exception like that and ignore the actual value and
assume it will be what you think it will be. This code is a bug waiting
to happen, and an incredibly difficult one to track down.

Further, the Close call should be in a finally block. Or, better, the
FileStream instantiation should be within a using statement.

--
-glenn-
Aug 16 '07 #12
Additionally, the assumption that all other programs will open a CSV
file exclusively is incorrect as well.

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

"GlennDoten" <gd****@gmail.comwrote in message
news:ef**************@TK2MSFTNGP06.phx.gbl...
Linda Liu [MSFT] wrote:
>Hi Brian,

When a .CSV file is opened by Excel or other programs except Notepad, it
is opened exclusively. We could make us of this feature to check if the
file is in use. That is, try to open this file to see if there's an
exception. If yes, this file is in use; otherwise, it's not in use.

The following is a sample.

public bool IsInUse(string filename)
{
try
{
System.IO.FileStream fs =
System.IO.File.OpenWrite(filename)
fs.Close();
return false;
}
catch (Exception exp)
{
return true;
}
}

Hope this helps.
If you have any question, please feel free to let me know.

Linda, how can you possibly assume that the only exception that may occur
in the code in the try block would be from a sharing violation?

Never, ever catch an Exception like that and ignore the actual value and
assume it will be what you think it will be. This code is a bug waiting to
happen, and an incredibly difficult one to track down.

Further, the Close call should be in a finally block. Or, better, the
FileStream instantiation should be within a using statement.

--
-glenn-

Aug 16 '07 #13
[Re-posting under my MSDN email. Would really appreciate an answer.]

Date: Thu, 16 Aug 2007 07:30:43 -0400
From: GlennDoten <gd****@gmail.com>
Subject: Re: Check for file in use
Newsgroups: microsoft.public.dotnet.languages.csharp

Linda Liu [MSFT] wrote:
Hi Brian,

When a .CSV file is opened by Excel or other programs except Notepad,
it is
opened exclusively. We could make us of this feature to check if the
file
is in use. That is, try to open this file to see if there's an
exception.
If yes, this file is in use; otherwise, it's not in use.

The following is a sample.

public bool IsInUse(string filename)
{
try
{
System.IO.FileStream fs =
System.IO.File.OpenWrite(filename)
fs.Close();
return false;
}
catch (Exception exp)
{
return true;
}
}

Hope this helps.
If you have any question, please feel free to let me know.
Linda, how can you possibly assume that the only exception that may
occur in the code in the try block would be from a sharing violation?

Never, ever catch an Exception like that and ignore the actual value and
assume it will be what you think it will be. This code is a bug waiting
to happen, and an incredibly difficult one to track down.

Further, the Close call should be in a finally block. Or, better, the
FileStream instantiation should be within a using statement.

--
-glenn-
Aug 17 '07 #14
Hi Glenn,

Thank you for pointing out the problem within my sample code!

Sincerely,
Linda Liu
Microsoft Online Community Support

Aug 21 '07 #15
Hi Brian,

How about the problem now?

If you need our further assistance, please feel free to let us know.

Thank you for using our MSDN Managed Newsgroup Support Service!

Sincerely,
Linda Liu
Microsoft Online Community Support

Aug 21 '07 #16

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

Similar topics

2
by: vishal | last post by:
hi is there anyway that i can check the size of file on client side before uploading file to server???? suppose the user uploads file of 10 mb then the server will know the size is 10 mb...
2
by: David Fickbohm | last post by:
People, I am trying to determine the creation date of files in a folder. I am using the following code to find the folder and confirm that files exist in the folder. If someone could give me an...
3
by: Chris | last post by:
Hi, In C# I tried to save a file from a generated file name. Just before launching the dialog I check for a valid file name to be sure. There for I used the method ValidateNames from the save...
1
by: Helixpoint | last post by:
I upload a file with the following code. Is there a way to check to see if the file is currently there before I upload? Dim s1 As String Dim s2 As String Dim pos As Integer s1 =...
2
by: mhadi | last post by:
Hello Please Help me!! The big bossman is screaming in my ear, I am only devloper of dotnet in my software house and know only to develop widows based application !! My boss wan't me to...
0
by: Terry | last post by:
Hi All, I'm having trouble checking in new webform or any type of file into ASP.NET web project's root directory. After I added new file into local SourceSafe controlled project, everytime I...
2
by: www.MessageMazes.com | last post by:
Greetings, I'm experimenting with an ASP page that reads data from a file name that is passed to it as a parameter, as in this page, which works, because the "good" file exists. ...
1
by: =?Utf-8?B?R2FuZXNoIE11dGh1dmVsdQ==?= | last post by:
Hello All, Our application write logs to a file in a folder. Before our application starts writing to that file, I want to check if the current user has write access to that file, for example,...
4
by: giftson.john | last post by:
Hi, I am creating an application which migrates all documents from one repository to another repository. Before migration i have to verify all the documents are unique. No duplicates has to be...
3
Frinavale
by: Frinavale | last post by:
Hi there! I'm hoping that someone knows how to check the size of a file before it is uploaded to the server using JavaScript. I have seen suggested solutions using an ActiveX control to check...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.