C# FileInUse?

D

DavidM

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;
}
}
 
Z

Zhi-xin Ye

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:
(e-mail address removed).
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.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/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top