473,800 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3076
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 GetLastWin32Err or 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.co m

"Brian Simmons" <ce******@newsg roup.nospamwrot e in message
news:%2******** ********@TK2MSF TNGP05.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(IOExcepti on) block. In the
catch
handle assume that file is in use. You can also check IOExceptio:HRes ult
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.co m

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

Put the code that opens the file into try/catch(IOExcepti on) block. In the
catch
handle assume that file is in use. You can also check IOExceptio:HRes ult
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 GetLastWin32Err or 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.co m

"Brian Simmons" <ce******@newsg roup.nospamwrot e in message
news:%2******** ********@TK2MSF TNGP05.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*********@Nn OwSlPiAnMk.comw rote in message
news:13******** *****@corp.supe rnews.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.co m
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 "IOExceptio n" 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 "NumberOfRetrie s"
mechanism would usually solve thits however). If a sharing violation is
detected then simply throw a (custom) "SharingViolati onException" with the
original "IOExceptio n" 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
GetHRForExcepti on method to get the HRESULT code of the exception. This
HRESULT is the result of calling the HRESULT_FROM_WI N32 macro on the error
code ERROR_SHARING_V IOLATION (which has a value of 32):

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

Looking in the code by calling the GetHRForExcepti on 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.co m

"Larry Smith" <no_spam@_nospa m.comwrote in message
news:%2******** **********@TK2M SFTNGP06.phx.gb l...
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 "IOExceptio n"
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
"NumberOfRetrie s" mechanism would usually solve thits however). If a
sharing violation is detected then simply throw a (custom)
"SharingViolati onException" with the original "IOExceptio n" 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
GetHRForExcepti on method to get the HRESULT code of the exception. This
HRESULT is the result of calling the HRESULT_FROM_WI N32 macro on the error
code ERROR_SHARING_V IOLATION (which has a value of 32):

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

Looking in the code by calling the GetHRForExcepti on 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 "IOExceptio n" 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 "IOExceptio n" 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
"IOExceptio n" 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_V IOLATION will be propagated back), it seems implausible
to me that MSFT would ever recommend using "GetHRForExcept ion()" 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

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

Similar topics

2
3866
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 after the file is uploaded to server which wastes the bandwidth so what i want to check is that the server first checks the size of file to upload and if it is o.k. then and then only the file will be uploaded..
2
3516
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 idea how to check a creation date it would be appreciated. Thanks dave def delete_old_files (t:\dm\~\users)
3
14540
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 dialog. The strange thing is that sometimes the save dialogue
1
1724
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 = file1.PostedFile.FileName pos = s1.LastIndexOf("\") + 1 s2 = s1.Substring(pos) file1.PostedFile.SaveAs("C:\Inetpub\wwwroot\xxxxx\images\machines\" & s2)
2
1939
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 devolope a page so that when a user clicks a link to to download a file the page check directory at client side(fixed lets name it "c:\download") and search for file say "blablav1.1.exe" (version will be updated)
0
1076
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 tried to check in new files, the error message box pops up saying "None of the items in the selection are valid for this operation". And then if you try to check in at the project level, the check in dialog box displays only web project file only not...
2
2463
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. http://mazes.com/asp-maze/customized.asp?file=good&firstname=jwk (make "your name is an amazing asp.general programmer" mazes. But when I try this page, with the "bad" file which does not exist, I'm
1
8067
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, "c:\temp\LogFile.txt". I see several articles for setting file access permissions, getting file access permissions for a given user or current user - but the current user could also gain write access to the same file not just by explicit permssion...
4
2649
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 uploaded. Event the document created date, modified date, filename can be different. How to find the document is duplidate. What i did is, i created a file and did save as and saved into another location. I am not able to find that the document...
3
8277
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 the file size; however, I'm not happy with this solution because my application is designed to work in multiple browsers and ActiveX is limited to Internet Explorer. I cannot check the file size on the web server because IIS throws the following...
0
9551
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10033
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4149
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
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.