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;
 
            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;
        }


     /// 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

9 comments:

  1. Thank you so much

    ReplyDelete
  2. This will not work, if file id opened in notepad

    ReplyDelete
  3. Good One!! My Issue solved, Thanks a lot.

    ReplyDelete
  4. If I want to force delete file used by another process. How we can achieve it.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete

Recommended Post Slide Out For Blogger