How to get the last file modified time ?

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);

}

}



Answer this question

How to get the last file modified time ?

  • enric12879

    You can use the File.GetLastWriteTimeUtc method to get the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.

    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();
            }
        }
    }

     




  • madmanmick

    Thanks you very much for your correction Truong Hont Thi!

    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();
    }
    }




  • anteriorsoft PVT.limited

    There are two problems with this snip:

    - need to use UtcNow instead
    - better use TotalDays. If you use Days, 7 days and 23 hours return 7.

  • KWFANG

    DateTime dt = File.GetLastWriteTimeUtc();
    if ((dt - DateTime.UtcNow).TotalDays > 7.0)
    {
    }

  • How to get the last file modified time ?