How To Set File Last Write Time in C#

In this article we will discuss about how to Set File Last Write Time in C#.

The SetLastWriteTime method of the File class is sets the last write date and time a file was written at. The method is a static method and expects the full path and a DateTime object. 

Here is a complete code sample that creates a new file if file does not exists and sets its last write time. 
 
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace GetSetFileLastWriteTimeSample  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             try  
  11.             {  
  12.                 string filename = @"c:\Temp\CSharpCorner.txt";  
  13.                 if (!File.Exists(filename))  
  14.                 {  
  15.                     File.Create(filename);  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     // Set LastWriteTime   
  20.                     File.SetLastWriteTime(filename, new DateTime(2000, 1, 1));  
  21.                 }  
  22.   
  23.                 // Get time  
  24.                 DateTime dt = File.GetLastWriteTime(filename);  
  25.                 Console.WriteLine("The last write time for this file was {0}.", dt);  
  26.   
  27.                 // Set last write time  
  28.                 File.SetLastWriteTime(filename, DateTime.Now);  
  29.   
  30.             }  
  31.             catch (Exception e)  
  32.             {  
  33.                 Console.WriteLine("The process failed: {0}", e.ToString());  
  34.             }  
  35.   
  36.             Console.ReadKey();  
  37.         }  
  38.     }  
  39. }