Delete latest created file from Directory

Kishork80
Posted by Kishork80 under C# category on | Points: 40 | Views : 2981
If we have list of files in our local folder and we want to delete the latest created file. The below code will do the same.

static void Main(string[] args)
{
//Pass the folder path where all files are existing
DirectoryInfo directInfo = new DirectoryInfo(@"C:\Kishor Kumar\Test");
FileInfo[] filelist = directInfo.GetFiles();
//make a list of all files using LINQ
var fileList = from n in filelist select new { FileName = n.FullName, CreationDate = n.CreationTime.ToLongDateString() };
//get the TOP FIRST file name using descending concept as the list is sorted by CreationDate
var fileLatest = (from m in fileList orderby m.CreationDate descending select m.FileName).First<string>();
Console.WriteLine(fileLatest );
//now delete the file
FileInfo file = new FileInfo(fileLatest );
file.Delete();
Console.WriteLine(fileLatest + " Deleted Successfully");
Console.Read();
}

Comments or Responses

Posted by: T.saravanan on: 3/30/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Kishork80,

Nice one.Kindly post your code inside the code tag its looking good.

Cheers :)

Login to post response