1

首先,我有一个 ftp 服务器中的文件名列表:

20130612_00
20130612_06
20130612_12

在 Main() 中,我有这样的东西

Public Main()
{
    //function to download all file from ftp server to local directory
    DownLoadFileFromFTP();

    //function to open the latest file in the local directory
    OpenLatestFileInLocal();
}

我想要一个根据本地目录中的文件名检查最新文件的功能。在这种情况下,最新的文件将是20130612_12

我的想法是首先删除特殊字符并仅获取数字编号,我现在有list<int>这样的:

2013061200
2013061206
2013061212

因此,如果我检查里面的最大值list<int>,我会知道哪个是最新的文件。

我的最终目标是通过执行打开最新文件OpenTxtFile(string fileName)

因此,我有一个类似下面的函数:

private void OpenLatestFileInLocal()
{
    // Get list of fileName from local directory
    // Ouput fileList_str = (string){20130612_00 , 20130612_06, 20130612_12}
    List<string> fileList_str = Directory.EnumerateFiles(localDir, "*.txt", SearchOption.AllDirectories).Select(Path.GetFileName).ToList();

    foreach (string fileName in fileList_str)
    {
        fileLIst_int.Add(Convert.ToInt32(RemoveSpecialCharacters(fileName)));
    }
    // Ouput: fileList_int = (int){2013061200 , 2013061206, 2013061212}

    int Latest = fileLIst_int.Max(); //Output: Latest = 2013061212

    // Problem is here.. my OpenTextFile function need to pass the fileName in string
    // But I identify the latest file as an (int) as 2013061212
    // I need to know 2013061212 is actually 20130612_12.txt
    // so that, I can pass the fileName into OpenTxtFile(string fileName)

    OpenTxtFile(fileName_Latest);

}

private void OpenTextFile(string fileName)
{

   // this function will only open file based on string fileName in local directory

}
4

1 回答 1

1

如果您已经在使用Linq,请填充一个匿名类来存储路径和解析日期(您也可以查看DateTime.ParseExact与转到 的对比int):

private void OpenLatestFileInLocal()
{
    var latestFile = Directory
        .EnumerateFiles(localDir, "*.txt", SearchOption.AllDirectories)
        .Select(path => new { Path = path, Date = DateTime.ParseExact(
            Path.GetFileNameWithoutExtension(path), "yyyyMMdd_HH", 
            CultureInfo.InvariantCulture) })
        .OrderByDescending(df => df.Date)
        .Select(df => df.Path)
        .FirstOrDefault();

    if (latestFile != null)
    {
        OpenTxtFile(latestFile);
    }
}
于 2013-06-12T04:17:19.653 回答