Delete newly created file from directory in C#

void deleteNewFile(string dirPath)
{
DirectoryInfo directInfo = new DirectoryInfo(dirPath); //read directory to enumerate files
FileInfo[] filelist = directInfo.GetFiles();
 
var fileList = from n in filelist select new { FileName = n.FullName, CreationDate = n.CreationTime.ToLongDateString() }; //get list of files by creationtime
 
var latestFile = (from m in fileList orderby m.CreationDate descending select m.FileName).First<string>(); //get the first file from the sorted list (descending order)
Console.WriteLine(latestFile); //display filename before deleting
 
FileInfo file = new FileInfo(latestFile);
file.Delete();
Console.WriteLine(latestFile + " has been deleted");
Console.ReadKey();
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.