
You want to get the DateTime that a file was last written to, using C# code. With File.GetLastWriteTime and File.GetLastWriteTimeUtc, you can get this time representation. Further, we can benchmark these methods to see the performance difference.
DateTime ExamplesThis program benchmarks the File.GetLastWriteTime and File.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 time the performance of the two methods.
Program that uses File.GetLastWriteTimeUtc [C#]
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 nsResult. We can see from this simple program that File.GetLastWriteTimeUtc is the faster method—it's about 10% faster. I discovered this by looking at File.GetLastWriteTime in IL Disassembler. Internally, File.GetLastWriteTime simply calls into File.GetLastWriteTimeUtc and then calls ToLocalTime. If you don't really need a local time, File.GetLastWriteTimeUtc is faster.
IL Disassembler Tutorial
The performance difference between File.GetLastWriteTime and File.GetLastWriteTimeUtc 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

We called both File.GetLastWriteTime and File.GetLastWriteTimeUtc. The latter method is more efficient because it simply does less and does not convert the time for you. As a final note, the FileInfo type has LastWriteTime and LastWriteTimeUtc properties. These are essentially the same as the two methods shown in the example code.
FileInfo Examples File Handling