C# 如何列出文件夹中以数字开头的所有文件?
我有一个文件夹,里面有文件。 这些文件是:C# 如何列出文件夹中以数字开头的所有文件?,c#,file,select,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) { fo
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循环中,我需要检查文件名的第一个字母:
类似于:如果第一个字母是一个数字,那么写一行。您可以使用LINQ和
Char.IsDigit
:
var numberFiles = Directory.EnumerateFiles(fbd.SelectedPath).Where(f => Char.IsDigit(f[0]));
foreach(string fn in numberFiles)
Console.WriteLine(fn);
您可以使用LINQ和
Char.IsDigit
:
var numberFiles = Directory.EnumerateFiles(fbd.SelectedPath).Where(f => Char.IsDigit(f[0]));
foreach(string fn in numberFiles)
Console.WriteLine(fn);
您可以使用simple
Regex
过滤以数字开头的文件
var files = Directory.GetFiles(fbd.SelectedPath)
.Where(x=> Regex.IsMatch(Path.GetFileName(x), @"^\d"));
您可以使用simple
Regex
过滤以数字开头的文件
var files = Directory.GetFiles(fbd.SelectedPath)
.Where(x=> Regex.IsMatch(Path.GetFileName(x), @"^\d"));
您只需检查文件名的第一个字符是否为数字
string name = System.IO.Path.GetFileName(path);
int output;
bool isNumeric = int.TryParse(name[0].ToString(), out output);
if(isNumeric)
Console.WriteLine(System.IO.Path.GetFileName(path));
您只需检查文件名的第一个字符是否为数字
string name = System.IO.Path.GetFileName(path);
int output;
bool isNumeric = int.TryParse(name[0].ToString(), out output);
if(isNumeric)
Console.WriteLine(System.IO.Path.GetFileName(path));
当然,您已经具备了所需的一切—您知道如何提取文件名—现在您只需检查该名称的第一个字符。或者我遗漏了什么?当然你已经有了你所需要的一切-你知道如何提取文件名-现在你只需检查名字的第一个字符。或者我遗漏了什么?我认为这个例子涉及正则表达式有点太简单了。我认为这个例子涉及正则表达式有点太简单了。泰兄弟,这有助于lot@Stefan:不客气。记住接受一个答案:)泰兄弟,这有助于lot@Stefan:不客气。记住接受答案:)