Read a file with a partially unknown file name

I want to read in a text file, but I know only part of the file name. To be more specific, the file format is "FOO_yyyymmdd_hhmmss.txt", but when I start my program I will only know "FOO_yyyymmdd_" and ".txt". In other words, I want to read this file based only on the date, ignoring the "hhmmss" (time) part, because I will not know the time of this file, but only the date.

Here is part of what I have so far:

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();                
}

How can I read this file without knowing the whole chain in advance?

+4
source share
2 answers

Well, look for the files, then check that there is only one file to read:

  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 one file only
    var fileName = files[0];
    ...
  }
+2

*, DirectoryInfo.EnumerateFiles

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

FileName == null ,

, Null-Conditional Operator (?.) # 6.0

+4

Source: https://habr.com/ru/post/1618861/


All Articles