Home » c# » How to delete all files from a specific folder? [closed]

How to delete all files from a specific folder? [closed]

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:
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);

Questions:
Answers:

You can do it via FileInfo or DirectoryInfo:

DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);

And then recreate the directory

Questions:
Answers:
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

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

Questions:
Answers:

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);

Questions:
Answers:

Try this:

foreach (string file in Directory.GetFiles(@"c:\directory\"))
  File.Delete(file);

Questions:
Answers:

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);