Get last created or modified file name in a directory in asp.net using c#

In this tutorial you will learn how to get the last created or modified file name in a directory in asp.net using c#. Almost a week ago I got a requirement to get the last created file name in a directory, I done it successfully and then decided to share with you nice people on nice-tutorials.blogspot.com :). Below is the code snippet that will do what you want.

Get last created or modified file name in a directory in asp.net using c#

Method 1)

string filePath = @"~\FolderName\";
string completeFilePath = Server.MapPath(filePath);
var directory = new DirectoryInfo(completeFilePath);
var fileName = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
lblDisplayFileName.Text=fileName.ToString();


Method 2)

string filePath = @"~\FolderName\";
string completeFilePath = Server.MapPath(filePath);
var directory = new DirectoryInfo(completeFilePath);
var fileName = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();



filePath variable contains the name of the folder from which you want to get the last created or modified file name. completeFilePath contains the exact physical path of folder on the server, returned by Server.MapPath() function because it is not good approach to hard-code the physical file paths such as D:\MyWebsite\FolderName into your web application, the path of file can be changed if you want to move your application into production. OK. And then using LINQ query syntax I get the last created or modified file name. In my case, folder is placed on root so that's why I used ~\ .

Note:- Don't forget to include the System.Linq, System.Xml.Linq and  System.IO namespaces


So that's it, you got the name of most recent file in a directory. Lot of cheers!!!

0 comments: