Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to delete all files and folders in a directory?

Utilizing C#, how might I erase all records and folders from a directory, yet at the same time keep the root registry?
by

4 Answers

akshay1995
The following code will clear the folder recursively:

private void clearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);

foreach(FileInfo fi in dir.GetFiles())
{
fi.Delete();
}

foreach (DirectoryInfo di in dir.GetDirectories())
{
clearFolder(di.FullName);
di.Delete();
}
}
RoliMishra
You can try this:

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
sandhya6gczb
Use the following code

new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);

//Or

System.IO.Directory.Delete(@"C:\Temp", true);
pankajshivnani123
Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.

public static void Empty(this System.IO.DirectoryInfo directory)
{
foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}

This will then allow you to do something like..

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");

directory.Empty();

Login / Signup to Answer the Question.