如何使用 GetFiles() 搜索包含 doc 文件但排除 docx 文件?
How to use GetFiles() search to include doc files but excude docx files?
目前我正在像这样循环访问我的文件系统
For Each filename As String In Directory.GetFiles(sourceFolder, "*.doc")
然而,这是将 docx 文件包含到 GetFiles returns 的文件列表中。我希望只搜索 doc 文件而不是 docx。知道我是否可以在搜索模式中使用截断或停止搜索字符吗?
这是GetFiles
的默认行为,您可以使用LINQ做进一步的过滤。
var files = Directory.GetFiles(@"C:\test", "*.doc")
.Where(file=> file.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase))
.ToArray();//If you want an array back
Directory.GetFiles Method (String, String)
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".
考虑到您想要遍历文件并考虑这些方法的默认行为,我建议使用 EnumerateFiles 而不是 GetFiles。通过这种方式,您可以对当前文件的扩展名添加一个简单的检查
foreach(string filename in Directory.EnumerateFiles(sourceFolder, "*.doc"))
{
if(!filename.EndsWith("x", StringComparison.CurrentCultureIgnoreCase))
{
.....
}
}
作为 Linq 的唯一解决方案并不优雅,但仍然有效,并且没有创建目录中存在的所有文件名的数组
我不是 C# 程序员,所以可能会有语法错误,但我认为它可以解决您的问题。
foreach (FileInfo fi in di.GetFiles("*.doc")
.Where(fi => string.Compare(".doc", fi.Extension,
StringComparison.OrdinalIgnoreCase) == 0))
{
myFiles.Add(fi);
}
目前我正在像这样循环访问我的文件系统
For Each filename As String In Directory.GetFiles(sourceFolder, "*.doc")
然而,这是将 docx 文件包含到 GetFiles returns 的文件列表中。我希望只搜索 doc 文件而不是 docx。知道我是否可以在搜索模式中使用截断或停止搜索字符吗?
这是GetFiles
的默认行为,您可以使用LINQ做进一步的过滤。
var files = Directory.GetFiles(@"C:\test", "*.doc")
.Where(file=> file.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase))
.ToArray();//If you want an array back
Directory.GetFiles Method (String, String)
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".
考虑到您想要遍历文件并考虑这些方法的默认行为,我建议使用 EnumerateFiles 而不是 GetFiles。通过这种方式,您可以对当前文件的扩展名添加一个简单的检查
foreach(string filename in Directory.EnumerateFiles(sourceFolder, "*.doc"))
{
if(!filename.EndsWith("x", StringComparison.CurrentCultureIgnoreCase))
{
.....
}
}
作为 Linq 的唯一解决方案并不优雅,但仍然有效,并且没有创建目录中存在的所有文件名的数组
我不是 C# 程序员,所以可能会有语法错误,但我认为它可以解决您的问题。
foreach (FileInfo fi in di.GetFiles("*.doc")
.Where(fi => string.Compare(".doc", fi.Extension,
StringComparison.OrdinalIgnoreCase) == 0))
{
myFiles.Add(fi);
}