Hi all,
I had loop thru a directory whereby I would like to get the lastfileModified time of each file in this directory. If the last Modified time is more than 7 days, I would like to delete this file. Can anyone help me of how to code it
Part of my code is as follow:
private
void DeleteLogFile(string sourceDir){
string[] fileEntries = Directory.GetFiles(sourceDir); foreach (string fileName in fileEntries){
// how to get the last modified time and compare it if it is more than 7 days MessageBox.Show(fileName);}
}

How to get the last file modified time ?
Eric Gooden
Or you can use the FileInfo.LastWriteTimeUtc property:
private void DeleteLogFile(string sourceDir)
{
DirectoryInfo directory = new DirectoryInfo( sourceDir );
FileInfo[] files = directory.GetFiles();
foreach( FileInfo file in files )
{
TimeSpan difference = DateTime. UtcNow.Subtract( file.LastWriteTimeUtc );
if(difference.Days > 7)
{
file.Delete();
}
}
}
batmc
If you don't want the effect that Truong Hong Thi explains you can use this:
DirectoryInfo directory = new DirectoryInfo(@"c:\mydir");
FileInfo[] files = directory.GetFiles();
foreach(FileInfo file in files)
{
DateTime lastWriten = file.LastWriteTimeUtc;
double difference = (lastWriten - DateTime.UtcNow).TotalDays;
if( difference > 7D )
{
file.Delete();
}
}
amersa
if ((dt - DateTime.UtcNow).TotalDays > 7.0)
{
}
Claude Vernier
- need to use UtcNow instead
- better use TotalDays. If you use Days, 7 days and 23 hours return 7.