Check if file is locked or has a handle on it

C Sharp - C# (programming language)
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

Check if file is locked or has a handle on it

Post by dzcadii » Sun Mar 01, 2015 10:50 pm

Code: Select all

//Check if file is locked
        #region isfilelocked
        public virtual bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;

            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }

            //file is not locked
            return false;
        }
        #endregion



Post Reply