- 1 year ago
c# programmatically set or Clear 'Accessed' meta info of a file
Comment
1 / 1
In C#, you can programmatically set or clear the "Accessed" meta information of a file using the File.SetLastAccessTime
method from the System.IO
namespace. This method allows you to set the last access time of a file to a specific date and time. To clear the "Accessed" meta information, you can set the last access time to the current date and time.
Here's how you can do it:
- Set the "Accessed" meta information of a file to a specific date and time:
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "C:\\path\\to\\your\\file.txt";
// Set the desired date and time for the last access time
DateTime lastAccessTime = new DateTime(2023, 7, 1, 12, 0, 0);
try
{
File.SetLastAccessTime(filePath, lastAccessTime);
Console.WriteLine("Last access time set successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error setting last access time: {ex.Message}");
}
}
}
- Clear the "Accessed" meta information of a file (set it to the current date and time):
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "C:\\path\\to\\your\\file.txt";
try
{
File.SetLastAccessTime(filePath, DateTime.Now);
Console.WriteLine("Last access time cleared successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error clearing last access time: {ex.Message}");
}
}
}
Please note that changing the "Accessed" meta information of a file might require elevated permissions, especially if the file is in a system-protected location. Make sure your application has the necessary permissions to modify the file's attributes.