3

I have N files in a folder. Some information is written into them from time to time. There is no strict logic of how the information is added into them. Content of the files are not relevant.

How to get the last-modified time of every file, compare and choose the right one?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
HotTeaLover
  • 93
  • 1
  • 1
  • 7

3 Answers3

5

Namespace System.IO has classes that help you get information about the contents of the filesystem. Together with a little LINQ it's quite easy to do what you need:

// Get the full path of the most recently modified file
var mostRecentlyModified = Directory.GetFiles(@"c:\mydir", "*.log")
                                    .Select(f => new FileInfo(f))
                                    .OrderByDescending(fi => fi.LastWriteTime)
                                    .First()
                                    .FullName;

You do need to be a little careful here (e.g. this will throw if there are no matching files in the specified directory due to .First() being called on an empty collection), but this is the general idea.

Jon
  • 428,835
  • 81
  • 738
  • 806
1
var file = new DirectoryInfo(dirname)
                .GetFiles()
                .OrderByDescending(f => f.LastWriteTime)
                .FirstOrDefault();
I4V
  • 34,891
  • 6
  • 67
  • 79
0

Try this

    DirectoryInfo DR = new DirectoryInfo(@"Path to directory where files are stored");

    FileInfo FR = DR.GetFiles();

    foreach(FileInfo F in FR)
    {
          Console.WriteLine("Last Edit Time : {0}",F.LastWriteTime);
    }

Remeber to Add namespace

    using System.IO;