File.GetLastWriteTime does not throw an exception if the file does not exist

Lately I have been working in performance engineering and improvement of a big and complex enterprise class product for financial market. Typical to any product or app for financial market, this product also has to deal with high volume of data – so every second (actually millisecond) counts. While profiling the App with Ants Profiler I saw that one of the methods which is costly is spending considerable amount of time in .NET API File.Exists method. The method actually gets the last write time of a file using File.GetLastWriteTime(filePath) but before that it checks whether the file exists through File.Exists. The reason is to make sure to call File.GetLastWriteTime only when File exists so that it does not throw exception. Following was the code used –


So as I started looking I thought to check whether the assumption of using File.Exists is correct. To my surprise I found in MSDN that File.GetLastWriteTime does not throw an exception in case the file does not exist.

If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.

So I re-wrote the code in the following way and was able to remove the call to File.Exists method which was costly –


Note that I had to compare the time in UTC as File.GetLastWriteTime returns 12:00 midnight, January 1, 1601 A.D. in UTC time.

Over the next few blog entries I would share some more performance improvement tricks. Happy Profiling!