12.1. Manipulating File Attributes
Problem
You need to display or manipulate a file's attributes or timestamps.
Solution
To display a file's timestamps, you can use either the static methods of the File class or the instance properties of the FileInfo class. The static methods are GetCreationTime, GetLastAccessTime, and GetLastWriteTime. Each has a single parameter, the path and name of the file for which timestamp information is to be returned, and returns a DateTime value containing the relevant timestamp. For example:
public static void DisplayFileTimestamps(string path)
{
Console.WriteLine(File.Get CreationTime(path));
Console.WriteLine(File.Get LastAccessTime(path));
Console.WriteLine(File.Get LastWriteTime(path));
}The instance properties of the FileInfo class are CreationTime, LastAccessTime, and LastWriteTime. Each returns a DateTime value containing the respective timestamp of the file represented by the FileInfo object. The DisplayFileInfoTimestamps extension method allows you to report those values directly from a FileInfo:
public static void DisplayFileInfoTimestamps(this FileInfo fileInfo)
{
Console.WriteLine(fileInfo.CreationTime.ToString());
Console.WriteLine(fileInfo.LastAccessTime.ToString());
Console.WriteLine(fileInfo.LastWriteTime.ToString());
}To modify a file's timestamps, you can use either the static methods of the File class or the instance properties of the FileInfo class. The static methods are SetCreationTime, SetLastAccessTime, and SetLastWriteTime. All ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access