Thursday 19 April 2012

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

 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)
        {
            try
            {
                //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;
                
            }
        } 

No comments:

Post a Comment