Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Get the 5 newest (last modified) files from a directory

Is there a way I can store the file location of the 5 last modified files from a directory using Array?

I am currently using the following codes below to get the last file:

DateTime lastHigh = new DateTime(1900,1,1);
string highDir;
foreach (string subdir in Directory.GetDirectories(path)){
    DirectoryInfo fi1 = new DirectoryInfo(subdir);
    DateTime created = fi1.LastWriteTime;

    if (created > lastHigh){
        highDir = subdir;
        lastHigh = created;
    }
}

I'll be using Array to send multiple files to an email address as attachment.

UPDATE

I am currently using the codes below to get the last modified files after 1 minute:

string myDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                  "Test Folder");
var directory = new DirectoryInfo(myDirectory);
DateTime from_date = DateTime.Now.AddMinutes(-1);
DateTime to_date = DateTime.Now;
var files = directory.GetFiles().Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);

I want to store to list of file names coming from files

like image 531
abramlimpin Avatar asked Jul 09 '12 01:07

abramlimpin


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

While the answer Paul Phillips provided worked. It's worth to keep in mind that the FileInfo.LastWriteTime & FileInfo.LastAccessTime do not always work. It depends on how the OS is configured or could be a caching issue.

.NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong

File.GetLastWriteTime seems to be returning 'out of date' value

like image 102
Luv2Learn Avatar answered Oct 18 '22 18:10

Luv2Learn