Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Windows file creation dates in C#.NET

Is it possible that multiple files can be created at the exact same time? Well obviously it is possible in some cases (I don't know those cases) when I call FileInfo classes CreationTimeUtc() method, it gives me exactly same time string. I differentiate the files under the same folder from each other by looking at their creation time, but since sometimes the creation times are same it ruins my approach. In that case I need a proper identifier for files to identify a file even if it's renamed or changed. I don't know what kind of an identifier i can use for this purpose. Any help would be appreciated. I am using C# .net 4.5

Upvotes: 0

Views: 139

Answers (2)

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

I solved the problem by using GetFileInformationByHandle() method as follows :

private static string GetFilePointer(FileInfo fi)
    {
        var fs = fi.OpenRead();
        var ofi = new BY_HANDLE_FILE_INFORMATION();
        ulong fileIndex = 0;
        if (GetFileInformationByHandle((IntPtr)fs.Handle, out ofi))
        {
            fileIndex = ((ulong)ofi.FileIndexHigh << 32) + (ulong)ofi.FileIndexLow;
        }
        fs.Close();
        return fileIndex.ToString();
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);

    [StructLayout(LayoutKind.Sequential)]
    struct BY_HANDLE_FILE_INFORMATION
    {
        public uint FileAttributes;
        public FILETIME CreationTime;
        public FILETIME LastAccessTime;
        public FILETIME LastWriteTime;
        public uint VolumeSerialNumber;
        public uint FileSizeHigh;
        public uint FileSizeLow;
        public uint NumberOfLinks;
        public uint FileIndexHigh;
        public uint FileIndexLow;
    }

looks like a really neat way of having a file identifier on ntfs file systems, renames, content changes or moves doesn't affect it.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77354

To identify files, you may want to compute a checksum, so the content is identified, not the name or date or location. Have a look here.

Upvotes: 1

Related Questions