我想读取一个文本文件,但我只知道文件名的一部分。更具体地说,文件的格式为“ 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();
}
如何在不事先知道整个字符串的情况下读取此文件?
好吧,搜索文件,然后检查是否只有一个文件可以读取:
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];
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句