当文件名按数字顺序列出时,如何按数字范围筛选Directory.GetFiles()?
问题描述:
我想过滤从Directory.GetFiles()函数返回哪些文件。目录中的文件都是以增量顺序命名的6位数字的文本文件(例如:“200501.txt”,“200502.txt”,“200503.txt”等),我想输入通过2个文本框控件“开始发票号码”和“结束发票号码”仅返回该范围内的文件。当文件名按数字顺序列出时,如何按数字范围筛选Directory.GetFiles()?
当前的代码如下...
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string[] fileDir = Directory.GetFiles(fbd.SelectedPath);
string[] files = fileDir;
foreach (string loopfile in files)
{
int counter = 0;
string line;
//Gets invoice number from text file name
//This strips all unnecessary strings out of the directory and file name
//need to change substring 32 to depending directory using
string loopfileName = loopfile.Substring(32);
string InvoiceNumberLong = Path.GetFileName(loopfile);
string InvoiceNumber = InvoiceNumberLong.Substring(0,(InvoiceNumberLong.Length - 4)).ToString();
var controlCount = new List<string>();
var EndCount = new List<string>();
//Read through text file line by line to find all instances of "control" and "------" string
//adds all line position of these strings to lists
System.IO.StreamReader file = new System.IO.StreamReader(loopfile);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Control"))
{
controlCount.Add(counter.ToString());
}
if (line.Contains("------"))
{
EndCount.Add(counter.ToString());
}
counter++;
}
}
}
}
预先感谢您!
答
您不能使用GetFiles方法提供的内置过滤器,该过滤器只能通过通配符进行过滤。你可以用一些LINQ做到这一点:
var files = Directory.EnumerateFiles(path, "*.txt")
.Where(d => int.TryParse(Path.GetFileNameWithoutExtension(d), out var value) && value > min && value < max);
注意:使用C#7出变种,但是如果你没有使用最新的转换为以前的版本。
另外考虑使用'EnumerateFiles'而不是'GetFiles'。 – mjwills
是的你是对的,'EnumerateFiles'更好地改变了答案,以反映这 –
谢谢我会研究这个,现在就试试吧! – MegaByteMe