I save files in a specific folder at run time. After some time, I want to delete them programmatically. How do I delete all files from a specific folder?
Asked
Active
Viewed 1.4e+01k times
59
-
6possible duplicate of [how to delete all files and folders in a directory?](http://stackoverflow.com/questions/1288718/how-to-delete-all-files-and-folders-in-a-directory) – Didier Spezia Sep 06 '12 at 16:28
6 Answers
138
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);
Or in a single line:
Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

CloudyMarble
- 36,908
- 70
- 97
- 130
-
23An even shorter syntax using a method group: `Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);` – Yan Yankowski Sep 11 '13 at 07:44
-
2VB: Array.ForEach(Directory.GetFiles(folderPath), Sub(x) File.Delete(x)) – Brent Aug 07 '14 at 15:42
-
-
-
i am using single line code Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete); but when my directory is empty then its provide errors so how can check if there is file or not before this line of code.. – Pragnesh Apr 26 '16 at 12:06
-
-
15
You can do it via FileInfo or DirectoryInfo:
DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);
And then recreate the directory

RvdK
- 19,580
- 4
- 64
- 107
-
+1, this is probably the easiest way if you just want to trash the directory entirely, saves looping over every single file. – Arran Sep 06 '12 at 09:56
-
8Ok, but if this directory has specific user's permissions, you'll loose them. – Paolo Moretti Sep 06 '12 at 10:00
-
@PaoloMoretti: true. But I suspect the user created this temp directory himself. – RvdK Sep 06 '12 at 10:10
-
9
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}

LaGrandMere
- 10,265
- 1
- 33
- 41
5
Add the following namespace,
using System.IO;
and use the Directory
class to reach on the specific folder:
string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
File.Delete(fileName);

Peter Mortensen
- 30,738
- 21
- 105
- 131

Talha
- 18,898
- 8
- 49
- 66
3
Try this:
foreach (string file in Directory.GetFiles(@"c:\directory\"))
File.Delete(file);

logicnp
- 5,796
- 1
- 28
- 32
0
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);

Findus
- 130
- 9