C#

How to handle File access IO exception in C#

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 Files 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) The 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. Even though it is not the best approach this will do your work.

Use the below-given function

///
/// If file already open or in use by any other thread this function 
/// return true. Else this function return false
///
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).
           return true;
       }
       finally
       {
            if (fileStream != null)
            fileStream.Close();
       }

       //file not in use so return false
       return false;
 }

The usage sample of this new method is:

//D:\\test.xlsx is the file you are trying to open
if (IsFileInUse("D:\\test.xlsx"))
MessageBox.Show("File already in use");

 

Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

1 year ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

1 year ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

1 year ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

1 year ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

1 year ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

1 year ago