Convert the value of the current DateTime object to a Windows file time in C#

The DateTime.ToFileTime() method in C# converts the value of the current DateTime object to a Windows file time. A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (UTC).

This method is commonly used when working with file system operations, as Windows stores file timestamps in this format internally.

Syntax

Following is the syntax for the ToFileTime() method −

public long ToFileTime()

Return Value

The method returns a long value representing the Windows file time equivalent of the DateTime object. The value is expressed as the number of 100-nanosecond intervals since January 1, 1601 UTC.

Using ToFileTime() with Current Date and Time

Example

using System;

public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      long res = d.ToFileTime();
      Console.WriteLine("Windows file time = {0}", res);
   }
}

The output of the above code is −

Date = 10/16/2019 8:17:26 AM
Windows file time = 132156874462559390

Using ToFileTime() with Specific Date

Example

using System;

public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 05, 10, 6, 10, 25);
      Console.WriteLine("Date = {0}", d);
      long res = d.ToFileTime();
      Console.WriteLine("Windows file time = {0}", res);
   }
}

The output of the above code is −

Date = 5/10/2019 6:10:25 AM
Windows file time = 132019422250000000

Converting Back from File Time

You can also convert a Windows file time back to a DateTime object using the DateTime.FromFileTime() method −

Example

using System;

public class Demo {
   public static void Main() {
      DateTime original = new DateTime(2019, 05, 10, 6, 10, 25);
      Console.WriteLine("Original Date = {0}", original);
      
      long fileTime = original.ToFileTime();
      Console.WriteLine("Windows file time = {0}", fileTime);
      
      DateTime converted = DateTime.FromFileTime(fileTime);
      Console.WriteLine("Converted back = {0}", converted);
   }
}

The output of the above code is −

Original Date = 5/10/2019 6:10:25 AM
Windows file time = 132019422250000000
Converted back = 5/10/2019 6:10:25 AM

Conclusion

The ToFileTime() method provides a reliable way to convert DateTime objects to Windows file time format, which is essential for file system operations and interoperability with Windows APIs. The conversion represents time as 100-nanosecond intervals since January 1, 1601 UTC.

Updated on: 2026-03-17T07:04:36+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements