读取文件部分未知的文件

时间:2015-12-07 09:37:18

标签: c# file filestream

我想在文本文件中读取,但我只知道文件名的一部分。更具体地说,文件的格式是“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();                
}

如何在事先不知道整个字符串的情况下阅读此文件?

2 个答案:

答案 0 :(得分:4)

如何使用DirectoryInfo.EnumerateFiles

提供的通配符*
string FileName  = new DirectoryInfo(@"\\myServer1\files\")
             .EnumerateFiles(String.Format("FOO_{0:yyyymmdd}_*.txt", DateTime.Now))
             .FirstOrDefault()?.FullName; 

FileName == null表示找不到该文件

请注意,Null-Conditional Operator (?.)只能在C#6.0之后使用

答案 1 :(得分:2)

嗯,搜索文件,然后检查只有一个文件才能读取

  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];
    ...
  }