Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the oldest file in a directory fast using .NET?

Tags:

c#

.net

file-io

I have a directory with around 15-30 thousand files. I need to just pull the oldest one. In other words the one that was created first. Is there a quick way to do this using C#, other than loading them into a collection then sorting?

like image 616
JL. Avatar asked Mar 08 '10 00:03

JL.


People also ask

How to get the oldest file in the directory c#?

To retrieve them in sorted order by the date modified, use either of these C# statements. files = di. GetFiles("*. *").

How do I find the oldest files in a directory in Linux?

To search for a directory, use -type d. -printf '%T+ %p\n' prints the last modification date & time of file (defined by %T) and file path (defined by %p). The \n adds a new line. Sort | head -n 1 it sorts the files numerically and passes its output to the head command which displays the 1 oldest file.

How would you list Oldest first and newest ones last?

ls -lt (what Rahul used) lists the current directory in long format in order by modification date/time, with the newest first and the oldest last. ls -ltr is the reverse of that; oldest first and the newest last.


1 Answers

You will have to load the FileInfo objects into a collection & sort, but it's a one-liner:

FileSystemInfo fileInfo = new DirectoryInfo(directoryPath).GetFileSystemInfos()
    .OrderBy(fi => fi.CreationTime).First();

Ok, two lines because it's a long statement.

like image 164
Kirk Broadhurst Avatar answered Oct 12 '22 20:10

Kirk Broadhurst