Open In App

File.GetLastAccessTime() Method in C# with Examples

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

public static DateTime GetLastAccessTime (string path);

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



  • path: This is the specified file path.

Exceptions:
 

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



 




// C# program to illustrate the usage
// of File.GetLastAccessTime(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 GetLastAccessTime() function
        DateTime dt = File.GetLastAccessTime(myfile);
  
        // Getting the last access time
        Console.WriteLine("The last access time for this file was {0}.", dt);
    }
}

Executing: 
 

The last access time for this file was 5/4/2020 12:00:00 AM.

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

 




// C# program to illustrate the usage
// of File.GetLastAccessTime(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.SetLastAccessTime(myfile, new DateTime(2020, 5, 4));
  
        // Calling GetLastAccessTime() function
        DateTime dt = File.GetLastAccessTime(myfile);
  
        // Getting the last access time
        Console.WriteLine("The last access time for this file was {0}.", dt);
    }
}

Executing: 
 

The last access time for this file was 5/4/2020 12:00:00 AM.

Article Tags :
C#