C# Program to View the Access Date and Time of a File
Last Updated :
01 Nov, 2021
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.CreationTime
3. Get the file last access time using the LastAccessTime property.
createdtime = path.LastAccessTime
4. 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#
using System;
using System.IO;
class GFG{
static void Main()
{
DateTime createdtime = path.CreationTime;
Console.WriteLine( "File is created at: {0}" , createdtime);
createdtime = path.LastAccessTime;
Console.WriteLine( "File is accessed at lastly: {0}" , createdtime);
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
Share your thoughts in the comments
Please Login to comment...