如何从特定文件夹中删除所有文件?

时间:2022-02-16 07:08:39

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?

我在运行时将文件保存在特定文件夹中。过了一段时间,我想以编程方式删除它们。如何删除特定文件夹中的所有文件?

6 个解决方案

#1


134  

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

#2


15  

You can do it via FileInfo or DirectoryInfo:

您可以通过FileInfo或DirectoryInfo来完成:

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

And then recreate the directory

然后重新创建目录

#3


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

#4


5  

Add the following namespace,

添加以下命名空间,

using System.IO;

and use the Directory class to reach on the specific folder:

并使用Directory类到达特定文件夹:

string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
    File.Delete(fileName);

#5


3  

Try this:

尝试这个:

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

#6


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

#1


134  

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

#2


15  

You can do it via FileInfo or DirectoryInfo:

您可以通过FileInfo或DirectoryInfo来完成:

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

And then recreate the directory

然后重新创建目录

#3


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

#4


5  

Add the following namespace,

添加以下命名空间,

using System.IO;

and use the Directory class to reach on the specific folder:

并使用Directory类到达特定文件夹:

string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
    File.Delete(fileName);

#5


3  

Try this:

尝试这个:

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

#6


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