如何从C#目录中获取文件

时间:2016-04-06 08:42:14

标签: c# .net

我需要从服务器路径获取前缀为009的所有文件。 但是我的代码检索所有带有0000前缀的文件并不特别以009开头。

例如,我有文件“000028447_ ghf.doc”,“0000316647 abcf.doc”,“009028447_ test2.doc”,“abcd.doc”。

string [] files =Directory.GetFiles(filePath,"009*.doc)

给了我除“abcd.doc”之外的所有文件。但我需要“009028447_ test2.doc”。 如果我给Directory.GetFiles(filePath,“ab * .doc)它将检索”abcd.doc“,并且工作正常。但是当我试图给出像”009“或”00002“这样的模式时它不会按预期工作

2 个答案:

答案 0 :(得分:0)

您的代码段缺少模式中的结束引号字符。代码应该是:

string[] files = Directory.GetFiles(filePath, "009*.doc");

除此之外,它似乎按预期工作。我已经通过创建一个包含您在问题中提到的文件的文件夹来测试这个:

Contents of testfolder

接下来,我创建了一个控制台应用程序,它使用您的代码查找文件,并将所有结果打印到控制台。输出是预期的结果:

  

C:\ testfolder \ 009028447_ test2.doc

以下是控制台应用程序的完整代码:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string filePath = @"C:\testfolder";
        string[] files = Directory.GetFiles(filePath, "009*.doc");

        // Creates a string with all the elements of the array, separated by ", "
        string matchingFiles = string.Join(", ", files);

        Console.WriteLine(matchingFiles);
        // Since there is only one matching file, the above line only prints:
        // C:\testfolder\009028447_ test2.doc
    }
}

总之,代码有效。如果您获得其他结果,则您的设置或代码中必须存在其他未提及的差异。

答案 1 :(得分:-1)

如果(并且我没有检查),您确实只收到了错误的文件,您应该使用foreach或linq检查文件是否符合您的标准:

FOREACH:

List<string> arrPaths = new List<string>();
Foreach(string strPath in Directory.GetFiles(filePath,".doc"))
{
if(strPath.EndsWith(".doc") & strPath.StartsWith("009"))
arrPaths.Add(strPath);
}

的LINQ:

List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pths => pths.StartsWith("009") && pths.EndsWith(".doc")).ToList();

这两种方式都是解决方法而不是真正的解决方案,但我希望他们能够帮助:)

修改

如果你只想获取文件名,我会从你的strPath中减去filePath,如下所示:

FOREACH:

arrPaths.Add(strPath.Replace(filePath + "\\", ""));

的LINQ:

List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pt => pt.StartsWith("009") && pths.EndsWith(".doc")).Select(pths => pths.ToString().Replace(filePath + "\\", "").ToList();