Get File Time [C#]

This example shows how to get file time informations, when any file was created, last modified or accessed. To get file datetime info you can use either static methods of File class or instance methods of FileInfo class.

Get file times using File class

Use File class when you want to get just one specific time, for example if you are only interested in a file last modification time. To do this use static method File.GetLastWri­teTime with file path as a parameter. File class also provides static methods to get file creation time or file last access time. You can also get this times in UTC, e.g. to get file last write time in UTC use File.GetLastWri­teTimeUtc.

[C#]
// local times
DateTime creationTime = File.GetCreationTime(@"c:\file.txt");
DateTime lastWriteTime = File.GetLastWriteTime(@"c:\file.txt");
DateTime lastAccessTime = File.GetLastAccessTime(@"c:\file.txt");

// UTC times
DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\file.txt");
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\file.txt");
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\file.txt");

// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2007 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2007 6:16:04 PM

Get file times using FileInfo class

Use instance of FileInfo class when you want to get more than one file time or any other informations about the file (like file attributes). Advantage is that you will get all needed informations just in one disk access. See following example.

[C#]
FileInfo fileInfo = new FileInfo(@"c:\file.txt");

// local times
DateTime creationTime = fileInfo.CreationTime;
DateTime lastWriteTime = fileInfo.LastWriteTime;
DateTime lastAccessTime = fileInfo.LastAccessTime;

// UTC times
DateTime creationTimeUtc = fileInfo.CreationTimeUtc;
DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
DateTime lastAccessTimeUtc = fileInfo.LastAccessTimeUtc;

// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2007 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2007 6:16:04 PM

Files and Folders Examples


See also

by Texy2! -->;