gpt4 book ai didi

c# - 在 C# 中使用通配符查找文件

转载 作者:可可西里 更新时间:2023-11-01 03:01:15 33 4
gpt4 key购买 nike

我正在尝试从目录中查找文件:

String[] search1 = Directory.GetFiles(voiceSource, "85267-*.wav")
.Select(path => Path.GetFileName(path))
.ToArray();

String[] search2 = Directory.GetFiles(voiceSource, "85267 *.wav")
.Select(path => Path.GetFileName(path))
.ToArray();

但是在 search1 中,它选择了 85267-s.wav85267 -s.wav。但我只想选择 85267-s.wav

search2 运行良好。

我该怎么做?

最佳答案

您遇到的行为是因为短文件名。因为你会得到 85267-~1.WAV for 85267 -s.wav 并且因为它匹配你的通配符 "85267-*.wav" 你得到两个文件。

Directory.GetFiles Method (String, String) 中有解释

Because this method checks against file names with both the 8.3 file name format and the long file name format, a search pattern similar to "1.txt" may return unexpected file names. For example, using a search pattern of "1.txt" will return "longfilename.txt" because the equivalent 8.3 file name format would be "longf~1.txt".

解决方法您可以使用Directory.EnumerateFiles 首先选择符合您条件的两个文件,然后比较actual(long) 文件名部分使用 StartsWith。记住EnumerateFiles做惰性评估。

String[] search1 = Directory.EnumerateFiles(@"C:\test", "85267-*.wav")
.Where(file => Path.GetFileName(file).StartsWith("85267-"))
.Select(path => Path.GetFileName(path))
.ToArray();

关于c# - 在 C# 中使用通配符查找文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28070228/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com