Open In App

File.SetLastAccessTimeUtc() Method in C# with Examples

File.SetLastAccessTimeUtc(String, DateTime) is an inbuilt File class method which is used to set the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
Syntax: 

public static void SetLastAccessTimeUtc (string path, DateTime lastAccessTimeUtc);

Parameter: This function accepts two parameters which are illustrated below:



  • path: This is the file for which to set the access date and time information.
  • lastAccessTime: This is the specified last access date and time, expressed in UTC time.

Exceptions:

Below are the programs to illustrate the File.SetLastAccessTimeUtc(String, DateTime) 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.SetLastAccessTimeUtc() 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 the SetLastAccessTimeUtc() function
        // to set last access date and time
        File.SetLastAccessTimeUtc(myfile, new DateTime(2020, 5, 4, 4, 5, 7));
 
        // Getting the last access date and time
        DateTime dt = File.GetLastAccessTimeUtc(myfile);
        Console.WriteLine("The last access date and "+
             "time in UTC for this file was {0}.", dt);
    }
}

Output:  

The last access date and time in UTC for this file was 5/4/2020 4:05:07 AM.

Program 2: Initially, no file was created. Below code itself creates a file file.txt and prints the last access date and time.




// C# program to illustrate the usage
// of File.SetLastAccessTimeUtc() method
 
// Using System and System.IO namespaces
using System;
using System.IO;
 
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
 
        // Checking the existence of the file
        if (!File.Exists(path)) {
            File.Create(path);
        }
 
        // Calling the SetLastAccessTimeUtc() function
        // to set last access date and time
        File.SetLastAccessTimeUtc(path, new DateTime(2019, 5, 4, 4, 5, 7));
 
        // Getting the last access date and time
        DateTime dt = File.GetLastAccessTimeUtc(path);
        Console.WriteLine("The last access date and time "+
                      "in UTC for this file was {0}.", dt);
    }
}

Executing: 

The last access date and time in UTC for this file was 5/4/2019 4:05:07 AM.

Article Tags :
C#