[英]Read file with partially unknown filename
我想在文本文件中读取,但我只知道文件名的一部分。 更具体地说,文件的格式是“FOO_yyyymmdd_hhmmss.txt”但是在运行我的程序时,我只会知道“FOO_yyyymmdd_”和“.txt”。 换句话说,我想根据日期读取该文件,忽略“hhmmss”(时间)部分,因为我不知道该文件的时间,只知道日期。
这是我到目前为止的一部分:
ArrayList al = new ArrayList();
string FileName = "FOO_" + DateTime.Now.ToString("yyyymmdd") + "_" ; //how do I correct this, keeping in mind that I need the time as well?
string InPath = @"\\myServer1\files\";
string OutPath = @"\\myServer2\files\";
string InFile = InPath + FileName;
string OutFile = OutPath + @"faceOut.txt";
using (StreamReader sr = new StreamReader(InFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
al.Add(line);
}
sr.Close();
}
如何在不事先知道整个字符串的情况下读取此文件?
如何使用DirectoryInfo.EnumerateFiles提供的通配符*
string FileName = new DirectoryInfo(@"\\myServer1\files\")
.EnumerateFiles(String.Format("FOO_{0:yyyymmdd}_*.txt", DateTime.Now))
.FirstOrDefault()?.FullName;
FileName == null
表示找不到该文件
请注意, Null-Conditional运算符(?。)只能从C#6.0开始使用
好吧, 搜索文件,然后检查 theres只有一个文件要读:
var pathToSearch = @"\\myServer1\files\";
var knownPart = string.Format("FOO_{0:yyyymmdd}_", DateTime.Now);
var files = Directory
.EnumerateFiles(pathToSearch, knownPart + "??????.txt")
.Where(file => Regex.IsMatch(
Path.GetFileNameWithoutExtension(file).Substring(knownPart.Length),
"^(([0-1][0-9])|(2[0-3]))([0-5][0-9]){2}$"))
.ToArray();
if (files.Length <= 0) {
// No such files are found
// Probably, you want to throw an exception here
}
else if (files.Length > 1) {
// Too many such files are found
// Throw an exception or select the right file from "files"
}
else {
// There's one file only
var fileName = files[0];
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.