The following method will get you latest file. I used .Last() of Linq method to get latest one. The latest files id obtained by ordering LastWriteTime of ileinfo propery and take last one. But if you want latest Top ten files or something, order by descending on LastWriteTime and Take(10).
public string SearchLatestFile(string path, string extension, string searchstring)
{
DirectoryInfo di = null;
if (Directory.Exists(path))
{
di = new DirectoryInfo(path);
}
else
return "Directory Does not Exist";
string newestFile;
IEnumerable<system.io.fileinfo> fileList = di.GetFiles("*" + searchstring.ToLower() + "*");
IEnumerable<system.io.fileinfo> fileQuery =
from file in fileList
where (extension.ToLower().Contains(file.Extension.ToLower()))
orderby file.LastWriteTime
select file;
try
{
var FileSearchedResult = (from file in fileQuery orderby file.LastWriteTime select new { file.FullName, file.Name, file.CreationTime }).Last();
newestFile = FileSearchedResult.FullName;
FileSearchedResult = null;
fileList = null;
di = null;
return newestFile;
}
catch
{
fileList = null;
di = null;
return null;
}
}