How to check For File Lock (File in use) in C#?

Hello Friend's

Wish you a very happy new year. Hope you will be enjoy a lots in New Year.

In one of my project I have required to check whether file is in use or it’s available for writing.
There is no direct way in c# for checking file lock as per my knowledge.
But I had done this task in other way however this is not a good way but I have no option for this.
Look at below code.


  public void OperationWithFile()
            string filepath = "D:\\Test.xlsm";
            if(FileInUse(filepath) == false)
                MessageBox.Show("You can't operform operation. File already in Use");

        private bool FileInUse(string path)
                //if file is not lock then below statement will successfully executed otherwise it's goes to catch.
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
                return false;
            catch (IOException ex)
                    return true;

Code is self explanatory hope you easily understand it.

If you have any doubt then let me know.


Posted in |


Post a Comment