Ankur Bhargav Blog

Friday, May 24, 2013

How To check File Is Being Another Process ,How To Check File Lock,How To CHeck File is In Used In another Proces

Using System.IO;
public static Boolean IsFileLocked(FileInfo file)
        {
            FileStream stream = null;
 
            try
            {
                //Don't change FileAccess to ReadWrite, 
                //because if a file is in readOnly, it fails.
                stream = file.Open
                (
                    FileMode.Open, 
                    FileAccess.Read, 
                    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;
        }

No comments:

Post a Comment