Home >Backend Development >Golang >How to Get a File\'s Creation Date in Windows Using Go?
Retrieving File Creation Date in Windows using Go
Question: How can I access the creation date of a file in a Windows system using the Go programming language?
Answer: To retrieve the creation date of a file in Windows using Go, you can utilize the os.File's Sys method to obtain the system-specific data structure, specifically, the Win32FileAttributeData for Windows systems. The Win32FileAttributeData structure contains, among other fields, the CreationTime, which represents the creation timestamp of the file.
To demonstrate this approach:
import ( "os" "syscall" "time" ) func GetFileCreationTime(path string) (time.Time, error) { fileInfo, err := os.Stat(path) if err != nil { return time.Time{}, err } // Verify that the file information is compatible with Windows sysFileInfo, isWindows := fileInfo.Sys().(*syscall.Win32FileAttributeData) if !isWindows { return time.Time{}, nil } // Convert the nanosecond timestamp to a `time.Time` object return time.Unix(0, sysFileInfo.CreationTime.Nanoseconds()), nil }
Example Usage:
creationTime, err := GetFileCreationTime("./myfile.txt") if err != nil { // Handle file opening error } fmt.Println("File creation time:", creationTime)
By utilizing this approach, you can easily retrieve the creation date of a file in Windows systems using the Go programming language.
The above is the detailed content of How to Get a File\'s Creation Date in Windows Using Go?. For more information, please follow other related articles on the PHP Chinese website!