Apr 13, 2013

Delete Folder and all Sub-Folders and Files in c#

In this post, I am sharing code snippet to delete the specified directory and all its sub directory and files in C#.

In the solution we are using members of Directory Class to delete the files and folders which exists in System.IO Namespace. So, we have added namespace using System.IO in our solution
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sDirectoryPath;
            sDirectoryPath = "d:\\abc"; //set directory path to delete
            if (Directory.Exists(sDirectoryPath))
            {
                RemoveDirectories(sDirectoryPath);
            }
        }

        private static void RemoveDirectories(string sDirectoryPath)
        {
            //This condition is used to delete all files from the Directory
            foreach (string file in Directory.GetFiles(sDirectoryPath))
            {
                File.Delete(file);
            }
            //This condition is used to check all child Directories and delete files
            foreach (string subfolder in Directory.GetDirectories(sDirectoryPath))
            {
                RemoveDirectories(subfolder);
            }

            Directory.Delete(sDirectoryPath);
        }
    }
}

    Choose :
  • OR
  • To comment
No comments:
Write Comments