Mkusa Sakala
Mkusa Sakala

Reputation: 31

Getting file creationTime c#

While using WIN32_FIND_DATA to obtain the files with FindFirstFile and FindFNextFile, am trying to do a task that requires me to enumerate files from two different directories and subsequently I need to find out the files from the first directory which were created earlier than any of the files from the second directory. The trouble is the CreationTime function returns wrong, uniform values for all the files, something like 1/1/1601 3:00:00 AM. Does anyone know how to obtain the correct creation time? Maybe it's to do with FILETIME type for fCreationTime ,i don't know.

I have got...


> struct NameAndDate
>     {
>         public string Name;
>         public DateTime Date;
>         public NameAndDate(string name, DateTime date)
>         {
>             Name = name;
>             Date = date;
>         }
>     }    
     for (int i = 0; i < AllFiles.Count; i++)
>      tmp[i] = new NameAndDate(AllFiles[i], File.GetCreationTime(AllFiles[i]));

ALLFiles is a list of files in a given directory and i am storing the files in an array of type struct that holds the name of a file and it's creation time. This will make it easier for me to do my comparison task. Note that i have also tried to use ..

FileInfo fd = new FileInfo(AllFiles[i]);
 tmp[i] = new NameAndDate(AllFiles[i], fd.CreationTime);

Upvotes: 0

Views: 1318

Answers (2)

Koder101
Koder101

Reputation: 892

Correct version of your program --

public struct NameAndDate
     {
         public string Name;
         public DateTime Date;
         public NameAndDate(string name, DateTime date)
         {
             Name = name;
             Date = date;
         }
     }   
DirectoryInfo d = new DirectoryInfo(@"C:\TestPath");
FileInfo[] AllFiles = d.GetFiles("*.*");  // Whatever file type you want.

NameAndDate[] tmp = new NameAndDate[AllFiles.Length];
for (int i = 0; i < AllFiles.Length; i++)
    tmp[i] = new NameAndDate(AllFiles[i].Name, AllFiles[i].CreationTime);

foreach(var v in tmp)
    Console.WriteLine(v.Date);

Upvotes: 0

code4life
code4life

Reputation: 15794

You might want to consult the documentation, particularly the Remarks section:

https://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx

2 points it raises that you should find interesting

1 - May not be accurate:

This method may return an inaccurate value, because it uses native functions whose values may not be continuously updated by the operating system.

2 - It will return the date value you mentioned if the file was not found, for whatever reason:

If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.

Double check that the file names that you are enumerating do indeed exist...!

HTH,

Upvotes: 1

Related Questions