File.SetLastWriteTime() Method in C# with Examples
File.SetLastWriteTime(String) is an inbuilt File class method which is used to set the date and time that the specified file was last written to.
Syntax:
public static void SetLastWriteTime (string path, DateTime lastWriteTime);
Parameter: This function accepts two parameters which are illustrated below:
- path: This is the specified file for which to set the date and time information.
- lastWriteTime: This is the specified local last write date and time of the path.
Exceptions:
- 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 specified path, file name, or both exceed the system-defined maximum length.
- FileNotFoundException: The specified path was not found.
- UnauthorizedAccessException: The caller does not have the required permission.
- NotSupportedException: The path is in an invalid format.
- ArgumentOutOfRangeException: The lastWriteTime specifies a value outside the range of dates or times permitted for this operation.
Below are the programs to illustrate the File.SetLastWriteTime(String, DateTime) method.
Program 1: Before running the below code, a file file.txt is created with some contents shown below-
CSharp
using System;
using System.IO;
class GFG {
public static void Main()
{
string myfile = @"file.txt" ;
File.SetLastWriteTime(myfile, new DateTime(2020,
5, 4, 4, 5, 7));
DateTime dt = File.GetLastWriteTime(myfile);
Console.WriteLine( "The last written date and " +
"time for this file was {0}." , dt);
}
}
|
Output:
The last written date and time 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 written date and time.
CSharp
using System;
using System.IO;
class GFG {
public static void Main()
{
string path = @"file.txt" ;
if (!File.Exists(path)) {
File.Create(path);
}
File.SetLastWriteTime(path, new DateTime(2019,
5, 4, 4, 5, 7));
DateTime dt = File.GetLastWriteTime(path);
Console.WriteLine( "The last written date and " +
"time for this file was {0}." , dt);
}
}
|
Executing:
The last written date and time for this file was 5/4/2019 4:05:07 AM.
Last Updated :
26 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...