delete folder/files and subfolder

This looks about right: http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html

//to call the below method
EmptyFolder(new DirectoryInfo(@"C:\your Path"))


using System.IO; // dont forget to use this header

//Method to delete all files in the folder and subfolders

private void EmptyFolder(DirectoryInfo directoryInfo)
{
    foreach (FileInfo file in directoryInfo.GetFiles())
    {       
       file.Delete();
     }

    foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
    {
      EmptyFolder(subfolder);
    }
}

You can also do the same by using the DirectoryInfo instance method. I just faced this problem and I believe this can resolve your problem too.

var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);

System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);

deleteTheseFiles.Delete(true);

For more details have a look at this link as it looks like the same.


Directory.Delete(folder_path, recursive: true);

would also get you the desired result and a lot easier to catch errors.


The easiest way in my experience is this

Directory.Delete(folderPath, true);

But I am experiencing a problem with this function in a scenario when I am trying to create the same folder right after its deletion.

Directory.Delete(outDrawableFolder, true);
//Safety check, if folder did not exist create one
if (!Directory.Exists(outDrawableFolder))
{
    Directory.CreateDirectory(outDrawableFolder);
}

Now when my code tries to create some file in the outDrwableFolder it ends up in exception. like for instance creating image file using api Image.Save(filename, format).

Somehow this piece of helper function works for me.

public static bool EraseDirectory(string folderPath, bool recursive)
{
    //Safety check for directory existence.
    if (!Directory.Exists(folderPath))
        return false;

    foreach(string file in Directory.GetFiles(folderPath))
    {
        File.Delete(file);
    }

    //Iterate to sub directory only if required.
    if (recursive)
    {
        foreach (string dir in Directory.GetDirectories(folderPath))
        {
            EraseDirectory(dir, recursive);
        }
    }
    //Delete the parent directory before leaving
    Directory.Delete(folderPath);
    return true;
}

Tags:

C#