C# File.GetLastWriteTimeUtc Example

This C# article examines the File.GetLastWriteTimeUtc method in the System.IO namespace.
File.GetLastWriteTimeUtc gets the last time a file was written to. With it and the similar File.GetLastWriteTime, we get a DateTime representation. Further we benchmark these methods to see a performance difference.Benchmark
Example. This program benchmarks the GetLastWriteTime and GetLastWriteTimeUtc methods. Often these two methods are interchangeable in programs. We first call each method on the target file to prime the disk cache. Then we measure the performance.
C# program that uses File.GetLastWriteTimeUtc using System; using System.Diagnostics; using System.IO; class Program { static void Main() { const int m = 10000; File.GetLastWriteTime("C:\\perls.txt"); File.GetLastWriteTimeUtc("C:\\perls.txt"); var s1 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { DateTime d = File.GetLastWriteTime("C:\\perls.txt"); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { DateTime d = File.GetLastWriteTimeUtc("C:\\perls.txt"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.Read(); } } Output 30345.84 ns 27041.65 ns
We can see from this simple program that GetLastWriteTimeUtc is the faster method. It is about 10% faster. I discovered this in IL Disassembler. Internally GetLastWriteTime simply calls into GetLastWriteTimeUtc and then calls ToLocalTime.

Thus: If you do not need a local time, GetLastWriteTimeUtc (with the UTC) is faster.

IL Disassembler Tutorial
Discussion. The performance difference between these two methods will apply also to several other methods. The File type itself, and the FileInfo type, both contain methods that can optionally be called without the UTC suffix.
Method list File.GetCreationTime File.GetCreationTimeUtc File.GetLastAccessTime File.GetLastAccessTimeUtc File.GetLastWriteTime File.GetLastWriteTimeUtc FileInfo.CreationTime FileInfo.CreationTimeUtc FileInfo.LastAccessTime FileInfo.LastAccessTimeUtc FileInfo.LastWriteTime FileInfo.LastWriteTimeUtc
Summary. We called both File.GetLastWriteTime and GetLastWriteTimeUtc. The latter method is more efficient because it does less. The FileInfo type has LastWriteTime and LastWriteTimeUtc properties. These are the same as the two methods shown.FileInfo
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls