HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to delete all files and folders in a directory?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhowdeleteandfilesfoldersall

Problem

Using C#, how can I delete all files and folders from a directory, but still keep the root directory?

Solution

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

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}


If your directory may have many files, EnumerateFiles() is more efficient than GetFiles(), because when you use EnumerateFiles() you can start enumerating it before the whole collection is returned, as opposed to GetFiles() where you need to load the entire collection in memory before begin to enumerate it. See this quote here:


Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.

The same applies to EnumerateDirectories() and GetDirectories(). So the code would be:

foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}


For the purpose of this question, there is really no reason to use GetFiles() and GetDirectories().

Code Snippets

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

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}
foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}

Context

Stack Overflow Q#1288718, score: 1158

Revisions (0)

No revisions yet.