October 22, 2012

C# - Check File is being used by another process, if not delete files

Some times while try to deleting a file we may got a error message like
"It is being used by another person or program."

This means we can't delete a file, if it is being used.

I provide a solution to handle this kind of exception.

        /// <summary>
        /// This function is used to check specified file being used or not
        /// </summary>
        /// <param name="file">FileInfo of required file</param>
        /// <returns>If that specified file is being processed 
        /// or not found is return true</returns>
        public static Boolean IsFileLocked(FileInfo file)
            FileStream stream = null;
                //Don't change FileAccess to ReadWrite, 
                //because if a file is in readOnly, it fails.
                stream = file.Open
            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;
                if (stream != null)
            //file is not locked
            return false;

     /// This function is used to delete all files inside a folder 
     public static void CleanFiles()
            if (Directory.Exists("FOLDER_PATH"))
                var directory = new DirectoryInfo("FOLDER_PATH");
               foreach (FileInfo file in directory.GetFiles())
                  if(!IsFileLocked(file)) file.Delete(); 

Source: Internet