如何根据日期从文件夹中获取文件

时间:2012-11-22 14:33:08

标签: c# c#-2.0

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

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

现在我将所有日期时间都放在一个逗号分隔值的字符串中。现在我被困了。如何从中获取最小的并获取相关文件

EDIT2

注意:Framework是.NET 2.0

4 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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;
    }

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

答案 2 :(得分: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];

答案 3 :(得分: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;
            }
        }