Friday, May 24, 2013

How To Delete All Files And Folder

Using System.IO;

public static void CleanFiles(String FolderPath)
     {
            if (Directory.Exists(FolderPath))
            {
                var directory = new DirectoryInfo(FolderPath);
               foreach (FileInfo file in directory.GetFiles())
               { 
                  if(!IsFileLocked(file)) 
                       file.Delete(); 
               }
               foreach (DirectoryInfo subfolder in directory.GetDirectories())
                {
                    CleanFiles(subfolder);
                }
            }
     }

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