C# 读取文件名部分未知的文件

C# 读取文件名部分未知的文件,c#,file,filestream,C#,File,Filestream,我想读入一个文本文件,但我只知道文件名的一部分。更具体地说,该文件的格式是FOO_yyyymmdd_hhmmss.txt,但在运行我的程序时,我只知道FOO_yyyymmdd_和.txt。换句话说,我只想根据日期读取该文件,忽略hhmmss时间部分,因为我不知道该文件的时间,只知道日期 以下是我到目前为止所做的部分工作: ArrayList al = new ArrayList(); string FileName = "FOO_" + DateTime.Now.ToString("yyyym

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

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

如何使用可用于的通配符*

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

请注意,只能从C 6.0开始使用。好的,搜索文件,然后检查是否只有一个文件要读取:

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