Friday 25 March 2011

Find Last Modified File in a folder

Let me first explain the requriements & constraints and then arrive at the solution.
I have a folder in a designated path (here C:/Testing), in which there are a lot of files. My requirement need me to find a specific type of files (here *.txt) in the folder. Of all the files of that type, I have to choose only those files who have a specific name (here Hello) and get the one which was the latest modified.

Here we can see the folder with 6 text files.











5 of the files name contains "Hello", so they fulfill our criteria. Although the 6th file "little.txt" was latest modified of all the files, our logic should not choose it; instead it should choose "Hello4.txt" since it was the latest modified of the other 5 files, that matches our criteria.



string dirname = @"C:\Testing";
string[] txtFiles = System.IO.Directory.GetFiles(dirname,"*.txt");
DateTime lastmodified= Convert.ToDateTime("01/01/1900");
string LastModifiedfile = string.Empty;
foreach (string filenm in txtFiles)
{
if (filenm.Contains("Hello"))
{
if (File.GetLastWriteTime(filenm) > lastmodified)
{
lastmodified =
LastModifiedfile = filenm;
}
}
}
Response.Write(LastModifiedfile + File.GetLastWriteTime(filenm);" at "+lastmodified+" was last modified.");



Hence we successfully get the result as:

No comments: