Tuesday, May 25, 2010

How To: Get File Time [C#]

To get file time information like attributes and all or when any file was created, last modified or accessed. For getting this you can get file DateTime info by using 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.

// local times
DateTime creationTime = File.GetCreationTime(@"c:\Demo.txt");
DateTime lastWriteTime = File.GetLastWriteTime(@"c:\Demo.txt");
DateTime lastAccessTime = File.GetLastAccessTime(@"c:\Demo.txt");
// UTC times
DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\Demo.txt");
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\Demo.txt");
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\Demo.txt");
// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 5/25/2010 10:10:00 PM
Console.WriteLine(lastWriteTimeUtc);  // 5/25/2010 10:10:00 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 information's about the file (like file attributes). Advantage is that you will get all needed information's just in one disk access. See following example.



FileInfo fileInfo = new FileInfo(@"c:\Demo.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);     // 5/25/2010 10:10:00 PM
Console.WriteLine(lastWriteTimeUtc);  // 5/25/2010 10:10:00 PM


Hope this is useful.

No comments:

Post a Comment