【问题标题】:Stop implicit wildcard in Directory.GetFiles()在 Directory.GetFiles() 中停止隐式通配符
【发布时间】:2010-12-02 02:04:27
【问题描述】:
string[] fileEntries = Directory.GetFiles(pathName, "*.xml");

还返回foo.xml_之类的文件有没有办法强制它不这样做,或者我必须编写代码来过滤返回结果。

这与命令提示符下的dir *.xml 行为相同,但与在 Windows 资源管理器中搜索 *.xml 不同。

【问题讨论】:

    标签: c# file directory filter


    【解决方案1】:

    此行为是设计使然。来自MSDN(查看注释部分和给出的示例):

    带有文件扩展名的 searchPattern 正好三个字符返回 具有三个扩展名的文件或 更多字符,前三个 字符匹配文件扩展名 在 searchPattern 中指定。

    你可以限制如下:

    C# 2.0:

    string[] fileEntries = Array.FindAll(Directory.GetFiles(pathName,  "*.xml"),
        delegate(string file) {
            return String.Compare(Path.GetExtension(file), ".xml", StringComparison.CurrentCultureIgnoreCase) == 0;
        });
     // or
    string[] fileEntries = Array.FindAll(Directory.GetFiles(pathName,  "*.xml"),
        delegate(string file) {
            return Path.GetExtension(file).Length == 4;
        });
    

    C# 3.0:

    string[] fileEntries = Directory.GetFiles(pathName, "*.xml").Where(file =>
       Path.GetExtension(file).Length == 4).ToArray();
    // or
    string[] fileEntries = Directory.GetFiles(pathName, "*.xml").Where(file =>
        String.Compare(Path.GetExtension(file), ".xml",
            StringComparison.CurrentCultureIgnoreCase) == 0).ToArray();
    

    【讨论】:

    • 知道这种看似奇怪的行为的原因吗?旧版 8.3 文件名的东西?
    • 我的目标是 2.0 框架,所以我不能使用 => 语法。
    • @Dan:更新代码以使用匿名委托。 @Jon Seigel:是的,没错。 MSDN 链接上的另一个注释提到该方法“检查具有 8.3 文件名格式和长文件名格式的文件名。”
    • 你的第一个 C#2.0 有一个 *.txt,它应该是 *.xml。否则它完全符合我的需要。谢谢。
    • @Dan:谢谢,已更新。我在本地使用 .txt 文件进行测试,但在这里错过了 :)
    【解决方案2】:

    这是由于windows 8.3的搜索方式。如果您尝试搜索“*.xm”,您将得到 0 个结果。

    您可以在 .net 2.0 中使用它:

    string[] fileEntries = 
    Array.FindAll<string>(System.IO.Directory.GetFiles(pathName, "*.xml"), 
                new Predicate<string>(delegate(string s)
                {
                    return System.IO.Path.GetExtension(s) == ".xml";
                }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      相关资源
      最近更新 更多