Given a file, our task is to view the date and time of access to a file. So to do this we use the following properties of the FileSystemInfo class:
1. CreationTime: This property is used to get the time in which the file is created.
Syntax:
file.CreationTime
Where the file is the path of the file and it will return DateTime. A DateTime structure is set to the date and time that the specified file.
2. LastAccessTime: This property is used to get the time in which the file is lastly used/accessed.
Syntax:
file.LastAccessTime
It will return a DateTime which represents the time in which the current file was accessed.
3. LastWriteTime: This property is used to get the time in which the file or directory is lastly written/updated.
Syntax:
file.LastWriteTime
It will return a DateTime which represents the time in the current file that was last written.
Approach
1. Read the file by using the file path i.e., C://sravan//data.txt
2. Declare DateTime variable for accessing file time details using the CreationTime property.
DateTime createdtime = path.CreationTime3. Get the file last access time using the LastAccessTime property.
createdtime = path.LastAccessTime4. Get the file lastly written time using the LastWriteTime property.
createdtime = path.LastWriteTime
Example:
In this example, we are going to create a file in C drive with two lines of data and the file name is data.txt and the path is shown in the below image:
// C# Program to display the date
// and time of access of a file
using System;
using System.IO;
class GFG{
static void Main()
{
// Choose the file using file path
FileInfo path = new FileInfo("C://sravan//data.txt");
// Declare time variable using DateTime function
// This variable holds the time of the file in
// which it is created
DateTime createdtime = path.CreationTime;
// Get the file created time
Console.WriteLine("File is created at: {0}", createdtime);
// Get the file lastly accessed time
createdtime = path.LastAccessTime;
Console.WriteLine("File is accessed at lastly: {0}", createdtime);
// Get the file lastly updated/written time
createdtime = path.LastWriteTime;
Console.WriteLine("File is lastly written on: {0} ", createdtime);
}
}
Output:
File is created at: 10/23/2021 10:02:10 AM File is accessed at lastly: 10/23/2021 10:20:00 AM File is lastly written on: 10/23/2021 10:17:03 AM