tags:

views:

2102

answers:

5

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

I have this

System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(GetMessageDownloadFolderPath());

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

Is this the cleanest way to do it?

+4  A: 

hi

yes I would do it in the same way.

gsharp
+8  A: 

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()) directory.Delete(true);
}

This will then allow you to do something like..

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

directory.Empty();
Adam Robinson
The last line should be subDirectory.Delete(true) instead of directory.Delete(true).I just cut-and-pasted the code and it deleted the main directory itself.Thanks for the code it's great!
+2  A: 

This 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();
        }
    }
hiteshbiblog
+1  A: 

Based on the hiteshbiblog, you probably should make sure the file is read-write.

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

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

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}
zumalifeguard
+2  A: 

I know I'm eleven months late with this one but we can also show love for LINQ:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.GetFiles()
    .ToList().ForEach(f => f.Delete());

directory.GetDirectories()
    .ToList().ForEach(d => d.Delete(true));
rasx