C# - How to Get Last Access Time of File or Directory?

Learn, how to get and print the last access time of a file or directory using C# program?
Submitted by IncludeHelp, on November 02, 2017 [Last updated : March 26, 2023]

Given a file and a directory and we have to get and print their last access time using C# program.

To get last access time of file or directory in C#, we use File.GetLastAccessTime() method.

File.GetLastAccessTime()

This is a method of "File" class, and it returns the last access time of a file/directory specified with the path.

Syntax

File.GetLastAccessTime(path);

Parameter(s)

  1. path - Location of file or directory.

Last access time contain following detail:

  • Date
  • Month
  • Year
  • Hour
  • Minute
  • Second
  • AM/PM

C# program to get last access time of file or directory

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      DateTime dt1;
      DateTime dt2;

      dt1 = File.GetLastAccessTime("ABC.TXT");
      Console.WriteLine("Last Access Time of file(ABC.TXT) : " + dt1);

      dt2 = File.GetLastAccessTime("mydir");
      Console.WriteLine("Last Access Time of directory(mydir) : " + dt2);
    }
  }
}

Output

Last Access Time of file(ABC.TXT) : 10/31/2017 9:38:13 PM
Last Access Time of directory(mydir) : 10/31/2017 9:08:23 PM

Explanation

In the above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program.

C# File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.