How to delete files from a specific folder using datetime constraint (C# code)

To delete files from a specific folder you can use following code snippet written in c#.


foreach (FileInfo fileInformation in new DirectoryInfo(@”I:/TrialTesting/”).GetFiles())
{
  File.Delete(fileInformation.FullName);                        
}


However, you can delete files comparing “Date Modeified ” attribute . Have a look at the following code snippet. This will delete all files from folder except last five day’s files.


try
{
 DateTime systemDate = DateTime.Now;
 int DefaultDay = 5;
 foreach (FileInfo fileInformation in new DirectoryInfo(@”I:/TrialTesting/”).GetFiles())
 {
   TimeSpan difference;
   difference = systemDate - fileInformation.LastWriteTime;
   //Delete Files from Folder
   if (difference.Days >= DefaultDay)
   {
     File.Delete(fileInformation.FullName);
   }
 }                   
}
catch (Exception ex)
{
 MessageBox.Show(ex.Message.ToString());
}


You can download code here.

Thanks
A Rahim Khan

Advertisements
  1. No trackbacks yet.

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

%d bloggers like this: