且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除所有具有特定扩展名的文件?

更新时间:2022-11-28 08:08:22

请看此页面上的文章3:
http://bytes.com/topic/c-sharp/answers/226296-delete-files [^ ]

您想要的情况:

Have a look at post #3 on this page:
http://bytes.com/topic/c-sharp/answers/226296-delete-files[^]

What you want in your case:

foreach(string sFile in System.IO.Directory.GetFiles(path, "*.tempfile"))
{
    System.IO.File.Delete(sFile);
}


您需要先获取目录中与扩展名匹配的所有文件,然后再删除每个文件.

You need to get all the files in the directory that match the extension first, then delete each one.

string[] directoryFiles = System.IO.Directory.GetFiles(path, "*.tempfile");
foreach (string directoryFile in directoryFiles)
{
   System.IO.File.Delete(directoryFile);
}


您首先需要使用Directory.GetFiles方法来获取所有具有给定扩展名的文件.像这样:

You will first need to use Directory.GetFiles method to get all the files with given extension. Like this:

string[] filesToDelete = Directory.GetFiles("c:\\test", "*.txt");



然后,如果您使用的是.Net 3.0或更高版本,则可以使用以下代码:



Then, if you are using .Net 3.0 or higher, you can use this:

filesToDelete.ToList().ForEach(file => File.Delete(file));



或遍历数组元素并逐个删除每个项目.循环会更好,因为它可以让您处理无权删除文件或文件正在使用的情况.



Or loop through the array elements and delete each item one by one. A loop would be better since it would let you handle the cases where you do not have rights to delete a file or if the file is in use.