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.
- using System;
- using System.IO;
-
- namespace GetSetFileLastWriteTimeSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- string filename = @"c:\Temp\CSharpCorner.txt";
- if (!File.Exists(filename))
- {
- File.Create(filename);
- }
- else
- {
-
- File.SetLastWriteTime(filename, new DateTime(2000, 1, 1));
- }
-
-
- DateTime dt = File.GetLastWriteTime(filename);
- Console.WriteLine("The last write time for this file was {0}.", dt);
-
-
- File.SetLastWriteTime(filename, DateTime.Now);
-
- }
- catch (Exception e)
- {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
-
- Console.ReadKey();
- }
- }
- }