File.Setlastwritetimeutc() Method In C#

In this tutorial, you will explore the File.SetLastWriteTimeUtc Method in C# along with its syntax, parameters, and a practical example.

What is the File.SetLastWriteTimeUtc Method?

The File class within the System.IO namespace in C# provides the "File.SetLastWriteTimeUtc" method to assign a specific UTC (Coordinated Universal Time) value as the last write time for a file. By utilizing this method, you can update the file's last write time property, specifying the most recent modification or write operation performed on it.

Syntax:

It has the following syntax:

Example

public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
  • path: It is the path of the File whose last write time you wish to set.
  • lastWriteTimeUtc: The UTC time to set as the last write time for the File.
  • Exceptions:

  • UnauthorizedAccessException: In this exception, the caller does not possess the required permission to do the task.
  • ArgumentException: The path is invalid characters, all-white spaces, or an empty string.
  • PathTooLongException: The file name, path, or both exceed the maximum length set by the System.
  • NotSupportedException: File system last write time changes are not supported.
  • Key Points for the File.SetLastWriteTimeUtc Method:

There are several key points for the File.SetLastWriteTimeUtc method in C#. Some main points are as follows:

  • The SetLastWriteTimeUtc method allows you to explicitly set the last write time for a file to a specific UTC time.
  • The path parameter specifies the File that the method operates on.
  • This method modifies the date of an existing file; it does not create the File if it does not already exist.
  • Proper exception handling is crucial to deal with potential issues during the operation, such as insufficient permissions or unsupported file systems.
  • This method is commonly used in scenarios where accurate and consistent file timestamp information is essential, especially in applications dealing with File versioning, synchronization, or auditing.
  • Example:

Let's consider a scenario to demonstrate the utilization of the File.SetLastWriteTimeUtc method in the C# programming language.

Example

using System;
using System.IO;
class Demo
{
    static void Main()
    {
        string file_Path = "sample.txt";
        DateTime newLastWriteTimeUtc = DateTime.UtcNow;
        try
        {
            File.SetLastWriteTimeUtc(file_Path, newLastWriteTimeUtc);
            Console.WriteLine($"Last write time of {file_Path} set to {newLastWriteTimeUtc} (UTC).");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}

Output:

Output

An error occurred: Could not find file '/home/compiler/sample.txt'.

Explanation:

In this instance, the File.SetLastWriteTimeUtc method is employed to update the last modified time of the file named "sample.txt" to the current Coordinated Universal Time (UTC). The DateTime.UtcNow function is used to obtain the current UTC time.

It is essential to manage exceptions effectively as altering file properties can result in various challenges, like incorrect paths, authorization problems, or incompatible file formats. The sample try-catch block showcases a fundamental method for handling errors.

1. Setting Custom Last Write Time

Let's consider another scenario to demonstrate the utilization of the File.SetLastWriteTimeUtc functionality with a customized last modified time in C#.

Example

using System;
using System.IO;
class Demo
{
    static void Main()
    {
        string file_Path = "samplefile.txt";
        DateTime customLastWriteTimeUtc = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
        try
        {
            File.SetLastWriteTimeUtc(file_Path, customLastWriteTimeUtc);
            Console.WriteLine($"Last write time of {file_Path} set to {customLastWriteTimeUtc} (UTC).");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}

Output:

Output

An error occurred: Could not find file '/home/compiler/samplefile.txt'.

Explanation:

This code demonstrates the process of utilizing the File class to set a customized UTC last write time for a specific file, such as "samplefile.txt". It involves using the SetLastWriteTimeUtc method and implementing error handling to address any potential issues that may occur during the operation. It is crucial to incorporate effective exception handling in order to deal with unforeseen circumstances and enhance the resilience of your application.

2. Permission Issue

Example

using System;
using System.IO;
class Demo
{
    static void Main()
    {
        string file_Path = "samplefile.txt";
        DateTime newLastWriteTimeUtc = DateTime.UtcNow;
        try
        {
            File.SetAttributes(file_Path, FileAttributes.ReadOnly);
            File.SetLastWriteTimeUtc(file_Path, newLastWriteTimeUtc);
            Console.WriteLine($"Last write time of {file_Path} set to {newLastWriteTimeUtc} (UTC).");
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine($"Unauthorized access: {e.Message}");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}

Output:

Output

An error occurred: Could not find file '/home/compiler/samplefile.txt'.

Explanation:

In this instance, the code employs the File.SetAttributes method to mimic a file with read-only permissions and subsequently attempts to update the last write time; this code snippet illustrates the approach for addressing such scenarios. Effective exception handling is essential for dealing with unforeseen circumstances and upholding the dependability of your software.

3. Handling Exceptions

Example

using System;
using System.IO;class Demo
{
    static void Main()
    {
        string file_Path = "samplefile.txt";
        DateTime newLastWriteTimeUtc = DateTime.UtcNow;
        try
        {
            File.SetLastWriteTimeUtc(file_Path, newLastWriteTimeUtc);
            Console.WriteLine($"Last write time of {file_Path} set to {newLastWriteTimeUtc} (UTC).");
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"File not found: {e.Message}");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}

Output:

Output

File not found: Could not find file '/home/compiler/samplefile.txt'.

Explanation:

This code demonstrates the procedure for updating the last modification time of a file, handles specific and general exceptions that could occur, and offers detailed notifications based on the result.

Purpose and Usage

There exist various functions and applications of the File.SetLastWriteTimeUtc Method in C#. Some primary functions of this method include:

  • Update Timestamps: The primary objective is to adjust a file's most recent write time to a particular UTC value, signifying the last time the File was modified.
  • Cross-Platform Timestamp Management: This feature proves advantageous in scenarios where ensuring uniform file timestamps across multiple systems and time zones is essential.

Input Required

This code uses input(). Please provide values below: