Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

File.GetLastWriteTime() Method in C# with Examples

  • Last Updated : 10 Mar, 2021

File.GetLastWriteTime(String) is an inbuilt File class method which is used to return the date and time the specified file or directory was last written to.
Syntax: 
 

public static DateTime GetLastWriteTime (string path);

Parameter: This function accepts a parameter which is illustrated below: 
 

  • path: This is the specified file path.

Exceptions:
 

  • UnauthorizedAccessException: The caller does not have the required permission.
  • ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
  • ArgumentNullException: The path is null.
  • PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
  • NotSupportedException: The path is in an invalid format.

Return Value: Returns the date and time the specified file or directory was last written to.
Below are the programs to illustrate the File.GetLastWriteTime(String) method.
Program 1: Before running the below code, a file file.txt is created with some contents shown below:
 

file.txt

 

C#




// C# program to illustrate the usage
// of File.GetLastWriteTime(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
  
        // Calling GetLastWriteTime() function
        DateTime dt = File.GetLastWriteTime(myfile);
  
        // Getting the last write time
        Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}

Executing: 
 

The last write time for this file was 4/19/2020 4:43:24 AM.

Program 2: Before running the below code, a file was created shown below:
 

file.txt

 

C#




// C# program to illustrate the usage
// of File.GetLastWriteTime(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
  
        // Setting the date
        File.SetLastWriteTime(myfile, new DateTime(2020, 4, 3));
  
        // Calling GetLastWriteTime() function
        DateTime dt = File.GetLastWriteTime(myfile);
  
        // Getting the last write time
        Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}

Executing: 
 

The last write time for this file was 4/3/2020 12:00:00 AM.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!