如何列出以数字开头的文件夹中的所有文件?

时间:2016-09-12 10:00:53

标签: c# file select

我有一个包含文件的文件夹。 这些文件是:

file1.txt
opera.exe
12_pro.bin
15th edition.txt
myFile.txt

现在,我需要一个代码来获取以数字开头的文件

所以,只有这两个:

12_pro.bin
15th edition.txt

我有这个:

FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
    foreach (var path in Directory.GetFiles(fbd.SelectedPath))
    {
        Console.WriteLine(path); // full path
        Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
    }
Console.ReadLine();   

现在,我需要这样的东西: 在for循环中,我需要检查文件的名称,第一个字母: 类似于:如果第一个字母是数字,那么写行。

3 个答案:

答案 0 :(得分:4)

您可以使用LINQ和Char.IsDigit

var numberFiles = Directory.EnumerateFiles(fbd.SelectedPath).Where(f => Char.IsDigit(f[0]));

foreach(string fn in numberFiles)
    Console.WriteLine(fn);

答案 1 :(得分:1)

您只需检查文件名的第一个字符是否为数字。

ConnectionTester

答案 2 :(得分:0)

您可以使用简单的Regex来过滤以数字开头的文件。

var files = Directory.GetFiles(fbd.SelectedPath)
                     .Where(x=> Regex.IsMatch(Path.GetFileName(x), @"^\d"));