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

C# FileInUse?

Hi --

I have a project I am working on that needs to read a file that another
application is creating. The application will need to wait until the file is
no longer in use.

I have done some Googling and there doesn't appear to be a good way to do
this in .NET. I'm reading that some folks saying the below approach is bad
as it causing an exception and exceptions are too expensive and shouldn't be
used for these types of scenarios.

If someone can provide some sort of guadance or best practice, I'd
appreciate it.
static bool FileInUse(string path)
{
try
{
//Just opening the file as open/create
using (FileStream fs = new FileStream(path,
FileMode.OpenOrCreate))
{
//If required we can check for read/write by using
fs.CanRead or fs.CanWrite
}
return false;
}
catch (IOException ex)
{
//check if message is for a File IO
__message = ex.Message.ToString();
if (__message.Contains("The process cannot access the file"))
return true;
else
throw;
}
}

Jun 27 '08 #1
2 2885
On Tue, 24 Jun 2008 11:03:21 -0700, DavidM
<Da****@discussions.microsoft.comwrote:
I have a project I am working on that needs to read a file that another
application is creating. The application will need to wait until the
file is
no longer in use.

I have done some Googling and there doesn't appear to be a good way to do
this in .NET. I'm reading that some folks saying the below approach is
bad
as it causing an exception and exceptions are too expensive and
shouldn't be
used for these types of scenarios.
Actually, the main reason it's a bad technique is that it won't provide
the information you want. Even if that method returns "true", the file
could become inaccessible before you get a chance to try to open it again.

Exceptions are expensive, yes. But if you've got a thread that can't do
anything anyway until a file becomes accessible, what do you care whether
it wastes times processing an exception? :) I suppose the thread itself
would consume more CPU cycles, but since a thread like that ought to only
be retrying the file access every half-second, second, or longer anyway, a
few extra CPU cycles here and there aren't likely to hurt much.

So, the real fix is to not use a method like the one you posted, and
instead just keep trying to open the file for whatever use it is you
intend. Sleep the thread in between attempts, and when it finally
succeeds, proceed with the actual FileStream reference (or however you've
opened the file).

Pete
Jun 27 '08 #2
Hi, David

How about this issue now?

For checking a file is in use or not, a better approach would be to call
the CreateFile API directly.

If the CreateFile API executs successfully, it will return an open handle
to the specified file, device, named pipe, or mail slot, we can then create
a FileStream object from this hadnle.

If the execution of CreateFile API fails, we can call the
Marshal.GetLastWin32Error() method to get the last error code, if the last
error code is ERROR_SHARING_VIOLATION , it means the file we check is in
use.

A sample code for your information

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError =
true)]
private static extern SafeFileHandle CreateFile(string lpFileName,
FileSystemRights dwDesiredAccess, FileShare dwShareMode, IntPtr
securityAttrs, FileMode dwCreationDisposition, FileOptions
dwFlagsAndAttributes, IntPtr hTemplateFile);

const int ERROR_SHARING_VIOLATION = 32;

private FileStream OpenFileStream(string fileName)
{
while (true)
{
try
{
SafeFileHandle fileHandle = CreateFile(fileName,
FileSystemRights.Modify, FileShare.Write,
IntPtr.Zero, FileMode.OpenOrCreate,
FileOptions.None, IntPtr.Zero);
if (!fileHandle.IsInvalid)
{
FileStream fs = new FileStream(fileHandle,
FileAccess.ReadWrite);
return fs;
}
}
catch (IOException ex)
{
//Do something with the exception, which usually should
not occur.
//Probably re-throw the exception.
}
int lastError = Marshal.GetLastWin32Error();
if (lastError != ERROR_SHARING_VIOLATION)
{
//The last error is not about sharing violation.
//Something unexpected may have occured.
}
Thread.Sleep(2000);
}
}

Through this approach, we can avoid the expensive exception handling.

Please try these and let me know how things going.

Best Regards
Zhi-Xin Ye
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.
==================================================
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.

Jun 27 '08 #3

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

Similar topics

2
by: marc.gibian | last post by:
I am writing a small program in C#/.NET that reads input files as they arrive from other processes. Therefore, it is perfectly reasonable for a file to be busy while it is being deposited for use...
2
by: Saya | last post by:
Hi, In my web service, it has to return an image from a file located at a specific virtual dir. Another concurrent app, running on the server, is periodically modifying that particular file....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...

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.