I need a function to clear the entire content of a folder. ASP.Net
cannot delete folders if the folder is not empty.
Asked
Active
Viewed 1.1k times
0

Hossein Narimani Rad
- 31,361
- 18
- 86
- 116

dvdmn
- 6,456
- 7
- 44
- 52
-
1Related: http://stackoverflow.com/q/329355/497356 – Andrew Whitaker Mar 25 '13 at 13:34
-
Are any of the files in use? That could screw things up... I'm guessing that with all the solutions shown below, you're going to need some exception handling! – Matthew Watson Mar 25 '13 at 13:34
-
1-1 for asking a question that is fairly well covered already, and then answering it immediately yourself. – Mar 25 '13 at 13:37
-
Either you really don't know how to use google, or you are trying to up your own rep by answering your own question. – JeremyK Mar 25 '13 at 14:02
-
I just wanted to share idea of looping in files and folders. I m not pursuing reputation, (I only got 182 points in ~2 years). hopefully a moderator will delete the topic and no one else will waste their time no more.. – dvdmn Mar 25 '13 at 14:20
4 Answers
3
You can use DirectoryInfo, Delete method with parameter specifying whether to delete subdirectories and files :
DirectoryInfo di = new DirectoryInfo("c:\\path");
if (di.Exists)
di.Delete(true);

Antonio Bakula
- 20,445
- 6
- 75
- 102
3
I've done something similar today.
Try this:
foreach (string folder in Directory.GetDirectories("C:\path"))
{
Directory.Delete(folder, true);
}
The 'true' is for recursive. So that all subitems (files and folders) will be deleted.

Tomtom
- 9,087
- 7
- 52
- 95
3
You can use Directory.Delete, where the second parameter specifies:
public static void Delete(
string path,
bool recursive
)
recursive Type: System.Boolean true to remove directories, subdirectories, and files in path; otherwise, false.

Tigran
- 61,654
- 8
- 86
- 123
1
Here is the code I came up with to erase files in the folder first, and then the folder itself:
string[] folders = Directory.GetDirectories("C:\path");
foreach (string folder in folders){
string[] files = Directory.GetFiles(folder);
foreach (string file in files){
File.Delete(file);
}
Directory.Delete(folder);
}

dvdmn
- 6,456
- 7
- 44
- 52