C# find most recent file in dir

C# find most recent file in dir

Problem:

I need to find the most recently modified file in a directory. I know I can loop through every file in a folder and compare File.GetLastWriteTime but is there a better way to do this without looping?

Solution:

var directory = new DirectoryInfo("C:\\MyDirectory");

var myFile = (from f in directory.GetFiles()

orderby f.LastWriteTime descending

select f).First();

// or…

var myFile = directory.GetFiles()

.OrderByDescending(f => f.LastWriteTime)

.First();

Reference:

http://stackoverflow.com/questions/1179970/c-sharp-find-most-recent-file-in-dir

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s