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.

Example

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()) {
               file.Delete();
            }
            dir.Delete(true);
         }
      }
   }
}

Output

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements