Search code examples
c#last-modified

Is there a method that shows that a file was "last accessed" as opposed to "last modified", in C# or are they the same?


I want to check that the file was last accessed as opposed to last modified. I have the resources needed to check "last modified" information on MSDN, but wasn't sure if "last accessed" was a thing. I am under the impression that last modified means that something was written to a file/folder, rather than being accessed and timestamped.

I mostly googled, I haven't attempted any coding at all, it's more for an informational resource before I delve into making code.


Solution

  • Assuming:

    check that the file was last accessed

    means getting the time that the file was accessed last.

    Using File.GetLastAccessTime(path) I was able to get the last time the file was accessed. This uses system.io namespace.

    Example:

    static void Main(string[] args)
    {
        try
        {
            string path = @"C:\test.txt";
    
            if (!File.Exists(path))
            {
                File.Create(path);
            }
            //get original access time
            DateTime dt = File.GetLastAccessTime(path);
            Console.WriteLine("The last access time for this file was {0}.", dt);
    
            // Update the last access time.
            File.SetLastAccessTime(path, DateTime.Now);
            dt = File.GetLastAccessTime(path);
            Console.WriteLine("The last access time for this file was {0}.", dt);
            Console.Read();
        }
    
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
    

    Took the example from : File.GetLastAccessTime(String) Method