Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file with partially unknown filename

I want to read in a text file but I only know a part of the filename. To be more specific, the format of the file is "FOO_yyyymmdd_hhmmss.txt" but when running my program, I will only know "FOO_yyyymmdd_" and ".txt". In other words, I want to read that file based on just the date, ignoring the "hhmmss" (time) part for I will not know the time of that file, 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 string beforehand?

like image 847
Divan Avatar asked Mar 13 '23 23:03

Divan


1 Answers

How about using a wildcard * available with DirectoryInfo.EnumerateFiles

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

FileName == null means that the file was not found

Note that the Null-Conditional Operator (?.) can only be used from C# 6.0 onwards

like image 143
Perfect28 Avatar answered Apr 28 '23 12:04

Perfect28