How to delete all files and folders from a path in C#?

For deleting all the folders and its respective directories we can make us System.IO namespace available in C#. The DirectoryInfo() class provides the details of all sub directories and file in a directory.


Let us consider a directory Demo having two sub directories and has some files like below.

using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         DirectoryInfo di = new DirectoryInfo(@"D:\Demo");
         foreach (DirectoryInfo dir in di.GetDirectories()) {
            foreach (FileInfo file in dir.GetFiles()) {


output of the above code is

We could see that all the folders and its related files are deleted from the demo directory completely. Here GetDirectories() will fetch all the directories of the root directory (Demo) and GetFiles() will fetch all the files (Demo File 1, Demo File 2) present in that directory.

Updated on: 08-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started