簡體   English   中英

讀取文件部分未知的文件

[英]Read file with partially unknown filename

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

如何在不事先知道整個字符串的情況下讀取此文件?

如何使用DirectoryInfo.EnumerateFiles提供的通配符*

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

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

請注意, Null-Conditional運算符(?。)只能從C#6.0開始使用

好吧, 搜索文件,然后檢查 theres只有一個文件要讀:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM