Click here to Skip to main content
15,890,506 members
Articles / Programming Languages / Visual Basic
Article

FileTime: Getting and setting the file time in .NET

Rate me:
Please Sign up or sign in to vote.
3.28/5 (16 votes)
3 Aug 20055 min read 141.5K   3.6K   27   7
Getting and setting the file time in .NET.

Image 1

Introduction

When an application is deployed some developers set the date and time of all the files to the same date and time. FileTime is a simple utility that allows you to do this. FileTime sets a file's or group of files' creation date/time, last access date/time and last write date/time.

Background

A file or directory has the following date and time attributes associated with it:

  • Creation time - The date and time the file or directory was first created.
  • Last access time - The date and time the file or directory was last accessed.
  • Last write time - The date and time the file or directory was last written to.

These attributes are normally set by the operating system when the relevant event occurs on the file or directory. The .NET Framework provides some useful functions for getting and setting a file's date and time. The objects are in the System.IO namespace. The File and Directory objects provide a powerful set of methods, these include:

  • File - provides methods to:
    • Check whether a file exists.
    • Create, copy, move and delete a file.
    • Get and set a file's attributes.
    • Get and set a file's date and time.
    • Get and set a file's date and time in coordinated universal time (UTC).
    • Basic reading and writing of files.
  • Directory - provides methods to:
    • Check whether a directory exists.
    • Create, move and delete a directory.
    • Get and set a directory date and time.
    • Get and set a directory date and time in coordinated universal time (UTC).
    • Get and set the current working directory.
    • Get a directory's root, parent directory.
    • Get all the sub-directories or files in a directory.

Both the File and Directory objects contain the following methods to access the various date/times.

  • Creation time
    • GetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the creation date.
    • SetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the required creation date.
  • Last Access Time
    • GetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the last access date.
    • SetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the required last access date.
  • Last Write Time
    • GetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the last write date.
    • SetLastWriteTime
      • Parameter: Path to the file as a string.
      • Return: DateTime object with the required last write date.

To make life simple import the System.IO namespace into your code.

Visual C#

C#
using System.IO;

Visual Basic .NET

VB
Imports System.IO

Viewing the file time

The methods we use to obtain the date/time are all static. This means that we do not need to create a File object before we use these methods. We just need the File class name. You just need to pass the full file path to the method and this returns a DateTime object.

The following code assumes that there are labels to display the times. It checks whether the full file path/name exists. It then gets the file date and time and displays it in a label.

Visual C#

C#
string fileName = @"C:\MyPath\MyFile.txt";
if (File.Exists(fileName))
{
    label_CreationTime.Text =
             File.GetCreationTime(fileName).ToString();
    label_LastAccess.Text =
             File.GetLastAccessTime(fileName).ToString();
    label_LastWrite.Text =
             File.GetLastWriteTime(fileName).ToString();
}

Visual Basic .NET

VB
Dim fileName As String = "C:\MyPath\MyFile.txt"
If File.Exists(fileName) Then
    Label_CreationTime.Text =
             File.GetCreationTime(fileName).ToString
    Label_LastAccess.Text =
             File.GetLastAccessTime(fileName).ToString
    Label_LastWrite.Text =
             File.GetLastWriteTime(fileName).ToString
End If

In the FileTime application we only allow you to select files that exist. Also we use try and catch to handle any errors. The kind of error we are likely to experience is "the file is opened by another application when you try to access it". This kind of error also applies to the rest of the code examples in this article.

Viewing the directory time

The code for looking at a file's date and time also works with directories. After all a directory is just a special kind of file. But when you know you are dealing with a directory there is a better way. The Directory class has similar methods as the File class and they are used in the same way.

Visual C#

C#
string directoryPath = @"C:\MyPath";
if (Directory.Exists(directoryPath))
{
    label_CreationTime.Text =
        Directory.GetCreationTime(directoryPath).ToString();
    label_LastAccess.Text =
        Directory.GetLastAccessTime(directoryPath).ToString();
    label_LastWrite.Text =
        Directory.GetLastWriteTime(directoryPath).ToString();
}

Visual Basic .NET

VB
Dim directoryPath As String = "C:\MyPath"
If Directory.Exists(directoryPath) Then
    Label_CreationTime.Text =
        Directory.GetCreationTime(directoryPath).ToString
    Label_LastAccess.Text =
        Directory.GetLastAccessTime(directoryPath).ToString
    Label_LastWrite.Text =
        Directory.GetLastWriteTime(directoryPath).ToString
End If

Setting the file time

There are similar static methods in the File class for setting a file's date and time. You just need to pass the full file path to the method and a DateTime object is set as required.

Visual C#

C#
string fileName = @"C:\MyPath\MyFile.txt";
if (File.Exists(fileName))
{
    // Select the time for the file
    DateTime fileTime = DateTime.Now;
    File.SetCreationTime(fileName, fileTime);
    File.SetLastWriteTime(fileName, fileTime);
    File.SetLastAccessTime(fileName, fileTime);
}

Visual Basic .NET

VB
Dim fileName As String = "C:\MyPath\MyFile.txt"
If File.Exists(fileName) Then
    ' Select the time for the file
    Dim fileTime As DateTime = DateTime.Now
    File.SetCreationTime(fileName, fileTime)
    File.SetLastWriteTime(fileName, fileTime)
    File.SetLastAccessTime(fileName, fileTime)
End If

There are a couple of things you need to note about setting the last access time. We set the last access time last. If we don't do this then when we set the last write or creation time then this counts as a file access. The operating system will update the last access time to the current time. This is not what you want. Also any kind of access on the file updates the last access time. So if you check the last access time that has been set correctly then this updates the last access time. This is a catch 22 situation that you should keep in mind while testing.

Setting the directory time

The code for viewing a file time works with directories. However the code for setting a file time does not work with directories. You need to use the following code:

Visual C#

C#
string directoryPath = @"C:\MyPath";
if (Directory.Exists(directoryPath))
{
    // Select the time for the directory
    DateTime directoryTime = DateTime.Now;
    Directory.SetCreationTime(directoryPath,
                                  directoryTime);
    Directory.SetLastWriteTime(directoryPath,
                                  directoryTime);
    Directory.SetLastAccessTime(directoryPath,
                                  directoryTime);
}

Visual Basic .NET

VB
Dim directoryPath As String = "C:\MyPath"
If Directory.Exists(directoryPath) Then
    ' Select the time for the directory
    Dim directoryTime As DateTime = DateTime.Now
    Directory.SetCreationTime(directoryPath,
                                     directoryTime)
    Directory.SetLastWriteTime(directoryPath,
                                     directoryTime)
    Directory.SetLastAccessTime(directoryPath,
                                     directoryTime)
End If

Recursive function for setting the file DateTime

With the following function you can set the date and time of all the files and sub-directories within a given directory. The function takes a string that is the full path to a directory. It does not check whether this path represents a valid directory. It also takes a DateTime object. This is the date and time you wish to set for all the files and directories.

Visual C#

C#
private void RecurseFileTime(string DirectoryPath,
                                 DateTime FileTime)
{
    // Set the date/time for each sub directory
    foreach (string subDirectory in
                Directory.GetDirectories(DirectoryPath))
    {
        // Loop through each sub-sub directory
        RecurseFileTime(subDirectory, FileTime);

        // Set the date/time for the sub directory
        Directory.SetCreationTime(subDirectory,
                                          FileTime);
        Directory.SetLastWriteTime(subDirectory,
                                          FileTime);
        Directory.SetLastAccessTime(subDirectory,
                                          FileTime);
    }
    // Set the date/time for each file
    foreach (string fileName in
                  Directory.GetFiles(DirectoryPath))
    {
        File.SetCreationTime(fileName, FileTime);
        File.SetLastWriteTime(fileName, FileTime);
        File.SetLastAccessTime(fileName, FileTime);
    }
}

Visual Basic .NET

VB
Private Sub RecurseFileTime(ByVal DirectoryPath As String,
                                ByVal FileTime As DateTime)
    ' Set the date/time for each sub directory
    For Each subDirectory As String In
                    Directory.GetDirectories(DirectoryPath)
        ' Loop through each sub-sub directory
        RecurseFileTime(subDirectory, FileTime)

        ' Set the date/time for the sub directory
        Directory.SetCreationTime(subDirectory, FileTime)
        Directory.SetLastWriteTime(subDirectory, FileTime)
        Directory.SetLastAccessTime(subDirectory, FileTime)
    Next
    ' Set the date/time for each file
    For Each fileName As String In
                          Directory.GetFiles(DirectoryPath)
        File.SetCreationTime(fileName, FileTime)
        File.SetLastWriteTime(fileName, FileTime)
        File.SetLastAccessTime(fileName, FileTime)
    Next
End Sub

Note that this function can fail if access to the file or directory is denied. This could be because the file is read only or it is open. (If it is a directory then this includes being open in Windows Explorer) The version of this function in the FileTime application is a bit more complex as it does this error checking.

Conclusion

The basic method of getting and setting the different dates and times of files and directories has been demonstrated. This used static methods on the File and Directory objects. The FileTime application uses these methods but adds some extra error checking and options. You can view the source code for FileTime which is available in automationControls.

This is the first application/article that I have made public. It is not so complex. But I hope it is the first of some more interesting material that is in the pipeline.

History

  • July 2005: Version 1.0 - First version.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThanks Pin
Member 89997052-Sep-19 2:18
Member 89997052-Sep-19 2:18 
QuestionSetLastWriteTime does not work when trying to set remote machine folder Pin
Kaps Panwar28-Mar-17 0:58
Kaps Panwar28-Mar-17 0:58 
Bugtypo Pin
ClipFlair admin31-Oct-13 2:26
ClipFlair admin31-Oct-13 2:26 
GeneralUpdate for VS 2005 and above Pin
Massey Ferguson17-Feb-11 17:41
Massey Ferguson17-Feb-11 17:41 
GeneralMy vote of 5 Pin
topedev21-Nov-10 7:38
topedev21-Nov-10 7:38 
GeneralMust adjust for DST Pin
Cheeso8-Mar-09 12:18
Cheeso8-Mar-09 12:18 
Generalsuprise Pin
Huisheng Chen3-Aug-05 5:15
Huisheng Chen3-Aug-05 5:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.