c# - 删除 Doc 文件并保留 Docx 文件

标签 c# winforms

<分区>

我正在尝试删除一个文件夹中的 .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 类冲突。根据一般经验,为变量赋予与现有类相同的名称是一种坏习惯。

关于c# - 删除 Doc 文件并保留 Docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32399106/

相关文章:

c# - 如何在 C# (Winforms) 中的 DataGridView 中添加进度条列

c# - 从 C# 发送的 JSON 但未在 php 中作为 JSON 接收

c# - 从二维网格中的值获取索引

c# - 当文本更改以适合控件时调整文本大小

.net - 只读(但可删除)组合框

c# - TreeNode.BeginEdit() 的问题

c# - 面板固定位置

c# - LoadCompleted 在 WPF WebBrowser 控件中未触发

c# 获取括号后的第一个 ';'

c# - 是否可以使用 C# 从 Azure 服务访问 SharePoint Server 数据?