TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

How to handle File access IO exception

File accessing file you may get IO exception was unhandled, the process cannot access the file because it is being used by another process.The reason fot this exception may be lke,File you are trying to open not even exist, File is in process by another thread,File is already kept open etc.How to handle this exception.

 If you are a .net programmer you may be familiar with the below shown exception which says IO exception was unhandled, the process cannot access the file because it is being used by another process. In this article I explain the sample code to get rid of this exception.

 

At times, when you try to access a file programmatically you will get a message that File not accessible. In such cases you can find out various reasons for non-accessibility of the file like,

           1) File you are trying to open not even exist

           2) File is in process by another thread

           3) File is already kept open etc.

 

How can we identify that the file is not available for access before trying to open the file? See the below given code sample that you can use to identify whether the file is in use or not.

Here the IOException was captured to check whether the file is available for access or not.Eventhough it is not a best approach this will do your work.

Use the below given function      

      

///<summary>

        /// If file already open or in use by any other thread this function return true.

        /// Else this function return false

        ///</summary>

        protectedvirtualbool IsFileInUse(string filePath)

        {

            FileStream fileStream = null;

            FileInfo fInfo = newFileInfo(filePath);

            try

            {

               fileStream = fInfo.Open(FileMode.Open);

            }

            catch (IOException)

            {

                //File in use (file is already open or the file is locked by another thread).

                returntrue;

            }

            finally

            {

                if (fileStream != null)

                    fileStream.Close();

                       

            }

 

            //file not in use so return false

            returnfalse;

        }

    }

 

 

The usage sample of this new method is:

 

if (IsFileInUse("D:\\test.xlsx"))  //D:\\test.xlsx is the file you are trying to open 

 MessageBox.Show("File already in use");

 

 

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading