11.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 parameter, the path and name of the file whose timestamp information is to be returned, and returns a DateTime value containing the relevant timestamp. For example:

public void DisplayFileAttr(string path)
{
    Console.WriteLine(File.GetCreationTime(path).ToString( ));
    Console.WriteLine(File.GetLastAccessTime(path).ToString( ));
    Console.WriteLine(File.GetLastWriteTime(path).ToString( ));
}

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 void DisplayFileAttr(string path)
{
    FileInfo fileInfo = new FileInfo(path);

    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 of them take the ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.