
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Manipulating File Attributes
|
677
12.2 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 parame-
ter, 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 DisplayFileAttr(string path)
{
Console.WriteLine(File.GetCreationTime(path));
Console.WriteLine(File.GetLastAccessTime(path));
Console.WriteLine(File.GetLastWriteTime(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 following code illustrates their use:
public static void DisplayFileAttr(string path)
{
FileInfo fileInfo = new FileInfo(path);
Console.WriteLine(fileInfo.CreationTime);
Console.WriteLine(fileInfo.LastAccessTime);
Console.WriteLine(fileInfo.LastWriteTime);
}
Using an instance of the FileInfo class is preferable to using the equivalent ...