Get latest files from a directory

Scenario:

I want to delete files in a folder . I want to keep max 3  latest files and/or one week old.

quick code :

 var directoryName = @”C:\temp”;
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(directoryName);
Console.WriteLine(dirInfo.Attributes.ToString());
DateTime dtLastWeek = (DateTime.Now.AddDays(-7));
Console.WriteLine(“dtLastWeek {0}”, dtLastWeek);

var totalFiles =dirInfo.GetFiles().Count();
IList fileNames2 =
dirInfo.GetFiles().OrderByDescending(f => f.CreationTime).Where(
f => f.CreationTime < dtLastWeek).ToList();
var oldFilesCount = fileNames2.Count();
var remainingFileCount = (totalFiles – oldFilesCount);
while (remainingFileCount ❤ && fileNames2.Count>0)
{
fileNames2.RemoveAt(0);
remainingFileCount++;
}
foreach (System.IO.FileInfo fi in fileNames2)
{
fi.Delete();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s