Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
DateTime.ToFileTime() Method in C#
The DateTime.ToFileTime() method in C# converts the value of the current DateTime object to a Windows file time. Windows file time represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (UTC).
This method is particularly useful when working with file system operations, as Windows uses this format internally for file timestamps.
Syntax
Following is the syntax −
public long ToFileTime();
Return Value
The method returns a long value representing the current DateTime object as a Windows file time.
How It Works
The method performs the following conversion process −
Using ToFileTime() with Current DateTime
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);
// Convert back to verify
DateTime converted = DateTime.FromFileTime(res);
Console.WriteLine("Converted back = {0}", converted);
}
}
The output of the above code is −
Date = 10/16/2019 8:17:26 AM Windows file time = 132156874462559390 Converted back = 10/16/2019 8:17:26 AM
Using ToFileTime() with Specific DateTime
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);
// Calculate difference from epoch
DateTime epoch = new DateTime(1601, 1, 1);
TimeSpan difference = d.ToUniversalTime() - epoch;
Console.WriteLine("Total 100-nanosecond ticks = {0}", difference.Ticks);
}
}
The output of the above code is −
Date = 5/10/2019 6:10:25 AM Windows file time = 132019422250000000 Total 100-nanosecond ticks = 132019422250000000
Common Use Cases
-
File System Operations − Working with file creation, modification, and access times.
-
Windows API Integration − Interfacing with Windows APIs that expect file time format.
-
Database Storage − Storing timestamps in a compact, standardized format.
-
Network Protocols − Some protocols use Windows file time for timestamp representation.
Conclusion
The DateTime.ToFileTime() method converts a DateTime object to Windows file time format, represented as 100-nanosecond intervals since January 1, 1601 UTC. This method is essential for file system operations and Windows API integration where precise timestamp representation is required.
