-1

我在具有命名约定的文件夹中有多个文件

Name_MoreName_DDMMYYYY_SomeNumber_HHMMSS.txt

如何获取具有最旧日期和时间的文件(即最旧的 DDMMYYYY 和 HHMMSS)。

前任:

  • Name_MoreName_22012012_SomeNumber_072334.txt
  • Name_MoreName_22012012_SomeNumber_072134.txt
  • Name_MoreName_24012012_SomeNumber_072339.txt
  • Name_MoreName_22012012_SomeNumber_072135.txt

所以最旧的文件将是

Name_MoreName_22012012_SomeNumber_072134.txt

我怎样才能只取最旧的文件?

编辑 这是我到目前为止所做的......在forach循环中我正在一个一个地读取文件名

private void FileInformation(string fileName, ref string concatFile)
        {
            try
            {
                string completeFileName = fileName.Trim();
                string[] fileComponenets = completeFileName.Split('_');

                string fileDate = string.Empty;
                string fileTime = string.Empty;


                if (fileComponenets.Length > 0)
                {
                    fileDate = fileComponenets[4].Replace(".txt", "").Trim();
                    fileTime = fileComponenets[2].ToString();
                    concatFile = fileDate + "-" + fileTime;
                }

            }

            catch (Exception ex)
            {
                            }

        }

- 主功能

string fileStats = string.Empty;
 foreach (string filePath in arrFileCollection)
                {
                    if (filePath.ToLower().Contains("Name_MoreName_")&&
                        filePath.ToLower().Contains(".txt"))
                    {
                                                string concatFile = string.Empty;
                        FileInformation(filePath.Replace(dirPath, ""), ref concatFile);
                        fileStats = fileStats + "," + concatFile;
                    }
}

现在我在一个带有逗号分隔值的字符串中获取所有日期时间。现在我被困住了。我怎样才能取其中最小的并获取相关文件

编辑2

注意:框架是 .NET 2.0

4

4 回答 4

1
string oldestFile = Directory.EnumerateFiles(path)
                             .OrderBy(file => ExtractDateTimeFrom(file))
                             .First(); // FirstOrDefault

并编写将解析您的文件名并从中提取日期的方法:

public static DateTime ExtractDateTimeFrom(string fileName)
{
    Regex regex = new Regex(@".+_(\d\d\d\d\d\d\d\d)_.+_(\d\d\d\d\d\d).txt");
    var match = regex.Match(fileName);
    string dateString = match.Groups[1].Value + match.Groups[2].Value;
    return DateTime.ParseExact(dateString, "ddMMyyyyHHmmsss", null);
}

.NET 2.0最简单的解决方案:

string oldestFile = "";
DateTime oldestDate = DateTime.Max;

foreach(string fileName in Directory.GetFiles(path))
{
    DateTime date = ExtractDateTimeFrom(fileName);
    if (date < oldestDate)
    {
        oldestFile = fileName;
        oldestDate = date;
    }
}
于 2012-11-22T14:43:31.593 回答
1

使用 DirectoryInfo 和 FileInfo 类。例如,只是为了给出想法:

        IOrderedEnumerable<FileInfo> filesInfo =  new DirectoryInfo("D:\\")
                                                      .EnumerateFiles()
                                                      .OrderBy(f=>f.FullName);

更新:对于.NET 2.0,我建议您将比较逻辑与您的主代码分开......所以为什么不创建一个实现 IComparable 接口的自定义类型。

public class CustomFileInfo :IComparable<CustomFileInfo>
{
    public string Name { get; set; }
    public string MoreName { get; set; }
    public DateTime FileDate { get; set; }
    public int Number { get; set; }
    public DateTime FileTime { get; set; }

    public CustomFileInfo(string fileNameString)
    {
        string[] fileNameStringSplited = fileNameString.Split('_');
        this.Name = fileNameStringSplited[0];
        this.MoreName = fileNameStringSplited[1];
        this.FileDate = DateTime.ParseExact(fileNameStringSplited[2], "ddMMyyyy", null);
        this.Number = int.Parse(fileNameStringSplited[3]);
        this.FileTime = DateTime.ParseExact(fileNameStringSplited[4], "HHmmss", null);
    }

    public int CompareTo(CustomFileInfo other)
    {
        // add more comparison criteria here
        if (this.FileDate == other.FileDate) 
            return 0;
        if (this.FileDate > other.FileDate)
            return 1;
        return -1;
    }
}

然后在您的代码中,您可以使用 DirectoryInfo 简单地获取文件并比较每个文件...

    FileInfo[] filesInfo = new DirectoryInfo("D:\\").GetFiles();
    //set first file initially as minimum
    CustomFileInfo oldestFileInfo = new CustomFileInfo(filesInfo[0].FullName);

    for (int i = 1; i < filesInfo.Length; i++)
    {
            CustomFileInfo currentFileInfo = new CustomFileInfo(filesInfo[i].FullName);
        //compare each file and keep the oldest file reference in oldestFileInfo
            if (oldestFileInfo.CompareTo(currentFileInfo) < 0)
                oldestFileInfo = currentFileInfo;
    }

您可以优化代码以供使用并根据您的标准自定义比较代码。

于 2012-11-22T14:47:26.703 回答
1

用这个:

更新

List<string> address = new List<string>() { "Name_MoreName_22012011_SomeNumber_072334.txt",
            "Name_MoreName_22012012_SomeNumber_072134.txt",
            "Name_MoreName_24012012_SomeNumber_072339.txt",
            "Name_MoreName_22012012_SomeNumber_072135.txt",};
            DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
            dtfi.ShortDatePattern = "dd-MM-yyyy";
            dtfi.DateSeparator = "-";
            address = address.OrderBy(s => Convert.ToDateTime((s.Split('_')[2]).Insert(2, "-").Insert(5, "-"), dtfi)).ToList();
            string oldest = address[0];
于 2012-11-22T14:50:39.673 回答
1

像这样的东西?

        string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
        Regex rex          = new Regex(@"^.*_(\d+)\.txt");
        int date           = int.MaxValue;
        int oldestdate     = int.MaxValue;
        String oldestfile;
        foreach(String filePath in filePaths)
        {
            Match match = rex.Match(filePath);

            if(match.Success)
                date = int.Parse(match.Groups[0].Value);
            if (date < oldestdate)
            {
                oldestdate = date;
                oldestfile = filePath;
            }
        }
于 2012-11-22T14:53:01.783 回答