我正在尝试删除一个文件夹中的 .doc
文件,该文件夹也包含 .docx
文件。
这是我目前的尝试:
string[] files = Directory.GetFiles(Path, "*.doc", SearchOption.AllDirectories);
foreach (string f in files)
{
File.Delete(f);
}
删除扩展名为.doc
和.docx
的word文档。
我只想删除 .doc
文件并保留 .docx
文件。
Directory.GetFiles Method (String, String, SearchOption) 的 MSDN 文档包括这条注释:
When you use the asterisk wildcard character in a searchPattern such
as "*.txt", the number of characters in the specified extension
affects the search as follows:
•If the specified extension is exactly three characters long, the
method returns files with extensions that begin with the specified
extension. For example, "*.xls" returns both "book.xls" and
"book.xlsx".
•In all other cases, the method returns files that exactly match the
specified extension. For example, "*.ai" returns "file.ai" but not
"file.aif".
When you use the question mark wildcard character, this method returns
only files that match the specified file extension. For example, given
two files, "file1.txt" and "file1.txtother", in a directory, a search
pattern of "file?.txt" returns just the first file, whereas a search
pattern of "file*.txt" returns both files.
解决 Microsoft 以这种方式“提供帮助”的最简单方法是过滤 Directory.GetFiles
调用的结果:
string[] files = Directory.GetFiles(filesPath, "*.doc", SearchOption.AllDirectories);
foreach (string f in files.Where(f => Path.GetExtension(f) == ".doc"))
{
File.Delete(f);
}
我重命名了您的 Path
变量,因为它与包含静态 GetExtension
方法的 System.IO.Path
类冲突。根据一般经验,为变量赋予与现有类相同的名称是一种坏习惯。