To check whether a file is in use or not in .Net program

by jask2002 27. August 2012 23:11

As the saying goes, Prevention is better than cure. It is always better to check whether a file is in use or not before doing any file operation on it to avoid any unexpected IOException during the runtime.

Exception in question is:

System.IO.IOException: The process cannot access the file 'C:\Inetpub\XXX.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights,…)
at System.IO.FileStream..ctor(String path, FileMode mode)

 

Here is the simple code to make a file check using static method IsFileInUse

 

                if (FileInUse.IsFileInUse(fileName)) 
                { 
                    status = "File is in use"; 
                } 
                else 
                { 
                    status = "File is not in use"; 
                } 
    public static bool IsFileInUse(string filename) 
        { 
            bool locked = false; 
            FileStream fs = null; 
            try 
            { 
                fs = 
                     File.Open(filename, FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.None); 
            } 
            catch (IOException ) 
            { 
                //We are capturing IOException
                locked = true; 
            } 
            finally 
            { 
                if (fs != null) 
                { 
                    fs.Close(); 
                } 
            } 
            return locked; 
        } 
You can download the Complete Source code from OneCode site (I’ve recently checked in there) Smile

PayPal — The safer, easier way to pay online. Has this post helped you? Saved you? If you'd like to show your appreciation. Please buy me a coffee or make a small contribution toward blog's maintenance(to keep it Ads free )

Tags: , ,

.Net | C#

Comments (6) -

guest
guest People's Republic of China
8/28/2012 5:25:26 AM #

race condition.
another thread/process can open that file after this test and before you actually open the file.
not very useful.
you'd better catch the exception when you actually want to open the file.

Reply

Jas
Jas United States
8/28/2012 10:54:29 PM #

Well , it will not a create a race condition.
Try the code .. Either open the file (excel etc) after or before the code execution. There is no wait on each other to release any sort of lock.

Reply

YaronD
YaronD Israel
8/30/2012 10:42:17 AM #

Jas, of course there is a potential race condition.

For a use in a real application you'd want to check if the file is in use, and then, well, open the file to use it. Right? Because if you don't intend to open and use it then what's the point, you won't throw the exception anyway and there's no problem.

Between the time the IsFileInUse method returns, and the time your code opens the file, something else could get to the file and open/lock it. This is not an atomic operation.

if (FileInUse.IsFileInUse(fileName))
{
  status = "File is in use";
}
else
{
  status = "File is not in use";
  // Now something else can open the file and lock it. We're not in the middle of an atomic operation, ergo potential race condition. A lot can happen between IsFileInUse and now. Try to pause here and then go open the file with another program to verify, you really really can
  FileStream fsNew = null;    // We need to use it
  fsNew=File.Open(filename, FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.None);  // Opening with no exception checking since we incorrectly think it's not in use. Result -> exception is thrown.
}

There's such an obvious potential race condition there that I'm not sure where you're coming from...

Reply

sfdg
sfdg United States
9/14/2012 12:00:18 AM #

dg

Reply

Gary Lillywhite
Gary Lillywhite United States
8/31/2013 4:41:07 AM #

you have a great blog here! would you like to make some invite posts on my blog?

Reply

jask2002
jask2002 United States
9/1/2013 1:13:19 AM #

Thanks Gary. Please do the needful.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About me

Hi there,

My name is  Jas and I'm currently working with Microsoft IIS/ASP.Net Escalation services.  Services

 

Tag cloud

Month List

RecentComments

Comment RSS

TextBox

 

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.