다음을 통해 공유


DateTimeOffset.FromFileTime(Int64) 메서드

정의

지정된 Windows 파일 시간을 해당하는 현지 시간으로 변환합니다.

public:
 static DateTimeOffset FromFileTime(long fileTime);
public static DateTimeOffset FromFileTime (long fileTime);
static member FromFileTime : int64 -> DateTimeOffset
Public Shared Function FromFileTime (fileTime As Long) As DateTimeOffset

매개 변수

fileTime
Int64

틱으로 표현된 Windows 파일 시간입니다.

반환

오프셋이 현지 시간 오프셋으로 설정된 fileTime 날짜 및 시간을 나타내는 개체입니다.

예외

fileTime 0보다 작습니다.

-또는-

fileTime DateTimeOffset.MaxValue.Ticks.

예제

다음 예제에서는 Windows API를 사용하여 WordPad 실행 파일에 대한 Windows 파일 시간을 검색합니다.

using System;
using System.IO;
using System.Runtime.InteropServices;

public struct FileTime
{
   public uint dwLowDateTime;
   public uint dwHighDateTime;

   public static implicit operator long(FileTime fileTime)
   {
      long returnedLong;
      // Convert 4 high-order bytes to a byte array
      byte[] highBytes = BitConverter.GetBytes(fileTime.dwHighDateTime);
      // Resize the array to 8 bytes (for a Long)
      Array.Resize(ref highBytes, 8);

      // Assign high-order bytes to first 4 bytes of Long
      returnedLong = BitConverter.ToInt64(highBytes, 0);
      // Shift high-order bytes into position
      returnedLong = returnedLong << 32;
      // Or with low-order bytes
      returnedLong = returnedLong | fileTime.dwLowDateTime;
      // Return long
      return returnedLong;
   }
}

public class FileTimes
{
   private const int OPEN_EXISTING = 3;
   private const int INVALID_HANDLE_VALUE = -1;

   [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
   private static extern int CreateFile(string lpFileName,
                                       int dwDesiredAccess,
                                       int dwShareMode,
                                       int lpSecurityAttributes,
                                       int dwCreationDisposition,
                                       int dwFlagsAndAttributes,
                                       int hTemplateFile);

   [DllImport("Kernel32.dll")]
   private static extern bool GetFileTime(int hFile,
                                          out FileTime lpCreationTime,
                                          out FileTime lpLastAccessTime,
                                          out FileTime lpLastWriteTime);

   [DllImport("Kernel32.dll")]
   private static extern bool CloseHandle(int hFile);

   public static void Main()
   {
      // Open file %windir%\write.exe
      string winDir = Environment.SystemDirectory;
      if (! (winDir.EndsWith(Path.DirectorySeparatorChar.ToString())))
         winDir += Path.DirectorySeparatorChar;
      winDir += "write.exe";

      // Get file time using Windows API
      //
      // Open file
      int hFile = CreateFile(winDir, 0, 0, 0, OPEN_EXISTING, 0, 0);
      if (hFile == INVALID_HANDLE_VALUE)
      {
         Console.WriteLine("Unable to access {0}.", winDir);
      }
      else
      {
         FileTime creationTime, accessTime, writeTime;
         if (GetFileTime(hFile, out creationTime, out accessTime, out writeTime))
         {
            CloseHandle(hFile);
            long fileCreationTime = (long) creationTime;
            long fileAccessTime = accessTime;
            long fileWriteTime = (long) writeTime;

            Console.WriteLine("File {0} Retrieved Using the Windows API:", winDir);
            Console.WriteLine("   Created:     {0:d}", DateTimeOffset.FromFileTime(fileCreationTime).ToString());
            Console.WriteLine("   Last Access: {0:d}", DateTimeOffset.FromFileTime(fileAccessTime).ToString());
            Console.WriteLine("   Last Write:  {0:d}", DateTimeOffset.FromFileTime(fileWriteTime).ToString());
            Console.WriteLine();
         }
      }

      // Get date and time, convert to file time, then convert back
      FileInfo fileInfo = new FileInfo(winDir);
      DateTimeOffset infoCreationTime, infoAccessTime, infoWriteTime;
      long ftCreationTime, ftAccessTime, ftWriteTime;

      // Get dates and times of file creation, last access, and last write
      infoCreationTime = fileInfo.CreationTime;
      infoAccessTime = fileInfo.LastAccessTime;
      infoWriteTime = fileInfo.LastWriteTime;
      // Convert values to file times
      ftCreationTime = infoCreationTime.ToFileTime();
      ftAccessTime = infoAccessTime.ToFileTime();
      ftWriteTime = infoWriteTime.ToFileTime();

      // Convert file times back to DateTimeOffset values
      Console.WriteLine("File {0} Retrieved Using a FileInfo Object:", winDir);
      Console.WriteLine("   Created:     {0:d}", DateTimeOffset.FromFileTime(ftCreationTime).ToString());
      Console.WriteLine("   Last Access: {0:d}", DateTimeOffset.FromFileTime(ftAccessTime).ToString());
      Console.WriteLine("   Last Write:  {0:d}", DateTimeOffset.FromFileTime(ftWriteTime).ToString());
   }
}
// The example produces the following output:
//    File C:\WINDOWS\system32\write.exe Retrieved Using the Windows API:
//       Created:     10/13/2005 5:26:59 PM -07:00
//       Last Access: 3/20/2007 2:07:00 AM -07:00
//       Last Write:  8/4/2004 5:00:00 AM -07:00
//
//    File C:\WINDOWS\system32\write.exe Retrieved Using a FileInfo Object:
//       Created:     10/13/2005 5:26:59 PM -07:00
//       Last Access: 3/20/2007 2:07:00 AM -07:00
//       Last Write:  8/4/2004 5:00:00 AM -07:00
open System
open System.IO
open System.Runtime.InteropServices
open FSharp.NativeInterop

[<Struct>]
type FileTime =
    val dwLowDateTime: uint
    val dwHighDateTime: uint

    static member ToLong(fileTime: FileTime) =
        // Convert 4 high-order bytes to a byte array
        let mutable highBytes = BitConverter.GetBytes fileTime.dwHighDateTime
        
        // Resize the array to 8 bytes (for a Long)
        Array.Resize(&highBytes, 8)

        // Assign high-order bytes to first 4 bytes of Long
        let returnedLong = BitConverter.ToInt64(highBytes, 0)
        
        // Shift high-order bytes into position
        let returnedLong = returnedLong <<< 32
        
        // Or with low-order bytes
        returnedLong ||| int64 fileTime.dwLowDateTime

let [<Literal>] OPEN_EXISTING = 3
let [<Literal>] INVALID_HANDLE_VALUE = -1

[<DllImport("Kernel32.dll", CharSet = CharSet.Unicode)>]
extern int CreateFile(string lpFileName,
                      int dwDesiredAccess,
                      int dwShareMode,
                      int lpSecurityAttributes,
                      int dwCreationDisposition,
                      int dwFlagsAndAttributes,
                      int hTemplateFile)

[<DllImport "Kernel32.dll">]
extern bool GetFileTime(int hFile,
                        nativeint lpCreationTime,
                        nativeint lpLastAccessTime,
                        nativeint lpLastWriteTime)

[<DllImport "Kernel32.dll">]
extern bool CloseHandle(int hFile)


// Open file %windir%\write.exe
let winDir = 
    let winDir = Environment.SystemDirectory
    let winDir =
        if winDir.EndsWith(string Path.DirectorySeparatorChar) then
            winDir
        else
            winDir + string Path.DirectorySeparatorChar
    winDir + "write.exe"

// Get file time using Windows API
// Open file
let hFile = CreateFile(winDir, 0, 0, 0, OPEN_EXISTING, 0, 0)

if hFile = INVALID_HANDLE_VALUE then
    printfn $"Unable to access {winDir}."
else
    let mutable creationTime = Unchecked.defaultof<FileTime>
    let mutable accessTime = Unchecked.defaultof<FileTime>
    let mutable writeTime = Unchecked.defaultof<FileTime>

    if GetFileTime(hFile, NativePtr.toNativeInt &&creationTime, NativePtr.toNativeInt &&accessTime, NativePtr.toNativeInt &&writeTime) then
        let fileCreationTime = FileTime.ToLong creationTime
        let fileAccessTime = FileTime.ToLong accessTime
        let fileWriteTime = FileTime.ToLong writeTime

        printfn $"File {winDir} Retrieved Using the Windows API:"
        printfn $"   Created:     {DateTimeOffset.FromFileTime fileCreationTime |> string:d}"
        printfn $"   Last Access: {DateTimeOffset.FromFileTime fileAccessTime |> string:d}"
        printfn $"   Last Write:  {DateTimeOffset.FromFileTime fileWriteTime |> string:d}\n"

// Get date and time, convert to file time, then convert back
let fileInfo = FileInfo winDir

// Get dates and times of file creation, last access, and last write
let infoCreationTime = fileInfo.CreationTime
let infoAccessTime = fileInfo.LastAccessTime
let infoWriteTime = fileInfo.LastWriteTime

// Convert values to file times
let ftCreationTime = infoCreationTime.ToFileTime()
let ftAccessTime = infoAccessTime.ToFileTime()
let ftWriteTime = infoWriteTime.ToFileTime()

// Convert file times back to DateTimeOffset values
printfn $"File {winDir} Retrieved Using a FileInfo Object:"
printfn $"   Created:     {DateTimeOffset.FromFileTime ftCreationTime |> string:d}"
printfn $"   Last Access: {DateTimeOffset.FromFileTime ftAccessTime |> string:d}"
printfn $"   Last Write:  {DateTimeOffset.FromFileTime ftWriteTime |> string:d}"


// The example produces the following output:
//    File C:\WINDOWS\system32\write.exe Retrieved Using the Windows API:
//       Created:     10/13/2005 5:26:59 PM -07:00
//       Last Access: 3/20/2007 2:07:00 AM -07:00
//       Last Write:  8/4/2004 5:00:00 AM -07:00
//
//    File C:\WINDOWS\system32\write.exe Retrieved Using a FileInfo Object:
//       Created:     10/13/2005 5:26:59 PM -07:00
//       Last Access: 3/20/2007 2:07:00 AM -07:00
//       Last Write:  8/4/2004 5:00:00 AM -07:00
Imports System.IO

Public Structure FileTime
   Public dwLowDateTime As UInteger
   Public dwHighDateTime As UInteger

   Public Shared Widening Operator CType(fileTime As FileTime) As Long
      Dim returnedLong As Long
      ' Convert 4 high-order bytes to a byte array
      Dim highBytes() As Byte = BitConverter.GetBytes(fileTime.dwHighDateTime)
      ' Resize the array to 8 bytes (for a Long)
      ReDim Preserve highBytes(7)

      ' Assign high-order bytes to first 4 bytes of Long
      returnedLong = BitConverter.ToInt64(highBytes, 0) 
      ' Shift high-order bytes into position
      returnedLong = returnedLong << 32
      ' Or with low-order bytes
      returnedLong = returnedLong Or fileTime.dwLowDateTime
      ' Return Long 
      return returnedLong
   End Operator
End Structure

Module modMain
   Private Const OPEN_EXISTING As Integer = 3
   
   Private Const INVALID_HANDLE_VALUE As Integer = -1
      
   Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" ( _
                            ByVal lpFileName As String, _
                            ByVal dwDesiredAccess As Integer, _
                            ByVal dwShareMode As Integer, _
                            ByVal lpSecurityAttributes As Integer, _
                            ByVal dwCreationDisposition As Integer, _
                            ByVal dwFlagsAndAttributes As Integer, _
                            ByVal hTemplateFile As Integer) _
           As Integer

   Private Declare Function GetFileTime Lib "Kernel32"( _
                            hFile As Integer, _
                            ByRef lpCreationTime As FileTime, _
                            ByRef lpLastAccessTime As FileTime, _
                            ByRef lpLastWriteTime As FileTime) _
            As Boolean 

   Private Declare Function CloseHandle Lib "Kernel32" ( _
                            hFile As Integer) _
           As Boolean
                        
   Public Sub Main()
      ' Open file %windir%\write.exe
      Dim winDir As String = Environment.SystemDirectory 
      If Not winDir.EndsWith(Path.DirectorySeparatorChar) Then _
         winDir += Path.DirectorySeparatorChar 
      windir += "write.exe"

      ' Get file time using Windows API
      '
      ' Open file
      Dim hFile As Integer = CreateFile(winDir, 0, 0, 0, _
                                       OPEN_EXISTING, 0, 0)
      If hFile = INVALID_HANDLE_VALUE Then
         Console.WriteLine("Unable to access {0}.", winDir)
      Else
         Dim creationTime, accessTime, writeTime As FileTime
         If GetFileTime(hFile, creationTime, accessTime, writeTime) Then
            CloseHandle(hFile)
            Dim fileCreationTime As Long = CType(creationTime, Long)
            Dim fileAccessTime As Long = CType(accessTime, Long)
            Dim fileWriteTime As Long = CType(writeTime, Long)

            Console.WriteLine("File {0} Retrieved Using the Windows API:", winDir)
            Console.WriteLine("   Created:     {0:d}", DateTimeOffset.FromFileTime(fileCreationTime).ToString())
            Console.WriteLine("   Last Access: {0:d}", DateTimeOffset.FromFileTime(fileAccessTime).ToString())
            Console.WriteLine("   Last Write:  {0:d}", DateTimeOffset.FromFileTime(fileWriteTime).ToString())
            Console.WriteLine() 
         End If   
      End If
      
      ' Get date and time, convert to file time, then convert back
      Dim fileInfo As New FileInfo(winDir)
      Dim infoCreationTime, infoAccessTime, infoWriteTime As DateTimeOffset
      Dim ftCreationTime, ftAccessTime, ftWriteTime As Long
      
      ' Get dates and times of file creation, last access, and last write
      infoCreationTime = fileInfo.CreationTime
      infoAccessTime = fileInfo.LastAccessTime
      infoWriteTime = fileInfo.LastWriteTime
      ' Convert values to file times
      ftCreationTime = infoCreationTime.ToFileTime()
      ftAccessTime = infoAccessTime.ToFileTime()
      ftWriteTime = infoWriteTime.ToFileTime()
      
      ' Convert file times back to DateTimeOffset values
      Console.WriteLine("File {0} Retrieved Using a FileInfo Object:", winDir)
      Console.WriteLine("   Created:     {0:d}", DateTimeOffset.FromFileTime(ftCreationTime).ToString())
      Console.WriteLine("   Last Access: {0:d}", DateTimeOffset.FromFileTime(ftAccessTime).ToString())
      Console.WriteLine("   Last Write:  {0:d}", DateTimeOffset.FromFileTime(ftWriteTime).ToString()) 
   End Sub
End Module
' The example produces the following output:
'    File C:\WINDOWS\system32\write.exe Retrieved Using the Windows API:
'       Created:     10/13/2005 5:26:59 PM -07:00
'       Last Access: 3/20/2007 2:07:00 AM -07:00
'       Last Write:  8/4/2004 5:00:00 AM -07:00
'    
'    File C:\WINDOWS\system32\write.exe Retrieved Using a FileInfo Object:
'       Created:     10/13/2005 5:26:59 PM -07:00
'       Last Access: 3/20/2007 2:07:00 AM -07:00
'       Last Write:  8/4/2004 5:00:00 AM -07:00

설명

Windows 파일 시간은 1601년 1월 1일 자정(C.E.) 12:00 자정 이후 경과된 100나노초 간격의 수를 나타내는 64비트 값입니다. UTC(협정 세계시). Windows는 파일 시간을 사용하여 애플리케이션이 파일을 만들거나, 액세스하거나, 파일에 쓸 때 기록합니다.

windows 파일 시간은 FILETIME 구조를 반환하는 GetFileTime 함수를 호출하여 Windows API를 통해 직접 액세스할 수 있습니다. 단일 함수 매개 변수는 파일 시간 정보를 검색할 파일의 핸들입니다. 파일 핸들은 CreateFile 함수를 호출하여 검색됩니다. FILETIME 구조체의 dwHighDateTime 멤버는 파일 시간의 4개의 높은 순서 바이트를 포함하고 dwLowDateTime 멤버는 4개의 낮은 순서 바이트를 포함합니다. 다음 예제에서는 Windows 파일 시간 값을 검색하고 DateTimeOffset 값으로 변환하는 방법을 보여 줍니다.

DateTime.ToFileTimeDateTime.ToFileTimeUtc 메서드를 호출하고 DateTimeOffset.ToFileTime 메서드를 호출하여 DateTimeOffset 값에서 DateTime 값에서 Windows 파일 시간 값을 만들 수도 있습니다.

적용 대상