Home > Mobile >  Get all files in a Directory and Get the newest one
Get all files in a Directory and Get the newest one

Time:11-03

I'm trying to get all the files in a directory and to get the name of the newest one.

List<string> NewFiles = new List<string>();
NewFiles = Directory.GetFiles(path,, "*.*", SearchOption.AllDirectories).ToList();
String lastItem = NewFiles.Last();

The problem is that i have 354 files in this folder and the last file i get from this is the file 99.

CodePudding user response:

Last() will get you the file name which happens to be enumerated as last file. There is no specific ordering, so this might not be the file last written.

When using DirectoryInfo.GetFiles instead, you get the information about the last modified time for each file.

var dirInfo = new DirectoryInfo(path);
var allFiles = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
var lastModifiedFile = allFiles.OrderBy(fi => fi.LastWriteTime).LastOrDefault();

CodePudding user response:

As Klaus said, you can use LastWriteTime property of FileInfo class to get the last file from that directory which is updated.

DirectoryInfo di = new DirectoryInfo(@"<Your directory path>");
//This will get all files in the top directory
var newestFile = di.GetFiles("*", SearchOption.TopDirectoryOnly) 
             .OrderByDescending(f => f.LastWriteTime)  //Sort(desc) by LastWriteTime
             .First();  //Take the first file

CodePudding user response:

If Just modify above query for specific pattern or specific file

string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();

Or if you want to run recursively

public static FileInfo GetNewestFile(DirectoryInfo directory) {
   return directory.GetFiles()
       .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
       .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
       .FirstOrDefault();                        
}

and call like this

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"your path"));
  • Related