triniMahn
triniMahn

Reputation: 278

Determine when File was Copied to a Directory in Windows 7

Problem:

On Windows XP the following code allowed me to determine if a file had been recently copied to a certain directory (written or overwritten) at some point on the current day.

Behaviour in Win XP:

If the file was written or overwritten in the directory on the current day, "LastAccessTime" would return a date on the current day.

Behaviour in Windows 7:

It returns the date listed under "Accessed" in the file properties (i.e. via explorer).

Notes:

Code:

DateTime today = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0);
FileInfo a = new FileInfo("file.txt");
if (a.LastAccessTime > today)
{//do something
}

Upvotes: 2

Views: 5966

Answers (3)

Mikael Svenson
Mikael Svenson

Reputation: 39695

You say written/overwritten so you should use LastWriteTime not LastAccessTime.

[edit]

And LastAccessTime seems to be default disabled in Win7 in order to save resources. Check out http://www.groovypost.com/howto/microsoft/enable-last-access-time-stamp-to-files-folder-windows-7/ on how to enable it.

Upvotes: 1

James Kovacs
James Kovacs

Reputation: 11661

Starting in Windows Vista, last access time is not updated by default. This is to improve file system performance. You can find details here:

http://blogs.technet.com/b/filecab/archive/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance.aspx

However, you're not interested in LastAccessTime, you're interested in LastWriteTime.

FileInfo a = new FileInfo(f);
if (a.LastWriteTime > DateTime.Today)
{
    //do something
}

BTW - Note DateTime.Today. It produces the same result as your "today" code.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504122

If you want to test for writing you should use LastWriteTime. For example, this code writes out all the files which have been modified today:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        DateTime today = DateTime.Today;
        foreach (FileInfo file in new DirectoryInfo(".").GetFiles())
        {
            if (file.LastWriteTime >= today)
            {
                Console.WriteLine(file.Name);
            }
        }
    }
}

I concur that LastAccessTime in Windows 7 seems not to be updated - I'm not sure why. This appears to be part of the file system though - looking at the directory with

dir /Ta

I see the same results as when I use LastAccessTime. Perhaps an update disabled updating the file system info on access.

Upvotes: 2

Related Questions