Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, April 25, 2016 9:32 AM
suppose every day when my apps run then it create files in specific folder with name pattern like log_ddMMyyyyhhmmss.xml
if my program run several time in a day then as many as log file will be created. so how could i delete files which has been created 7 days ago. i want to mean how could i keep only last seven days files and delete rest of the files which has been created 7 days ago. please guide me with sample code. thanks
All replies (5)
Monday, April 25, 2016 9:45 AM ✅Answered
var files = new DirectoryInfo(@"your-folder-path").GetFiles("*.xml");
foreach (var file in files)
{
if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(7))
{
File.Delete(file.FullName);
}
}
Monday, April 25, 2016 11:13 AM ✅Answered
Sudip,
One correction. Thanks Mike!
string[] files = Directory.GetFiles("YOUR_DIRECTORY");
foreach (string file in files)
{
FileInfo fInfo = new FileInfo(file);
if (fInfo.CreationTime < DateTime.Now.AddDays(-7))
fInfo.Delete();
}
Monday, April 25, 2016 10:42 AM
Sudip,
You can follow below line of code to delete all files which are longer than week.
string[] files = Directory.GetFiles("YOUR_DIRECTORY");
foreach (string file in files)
{
FileInfo fInfo = new FileInfo(file);
if (fInfo.LastAccessTime < DateTime.Now.AddDays(-7))
fInfo.Delete();
}
Monday, April 25, 2016 10:46 AM
fInfo.LastAccessTime
That doesn't return the creation date.
Monday, April 25, 2016 11:07 AM
Correct Mike! It gives last access date. I assumed, no one manually update the file. In this code your code is perfect.