📜  C#中的File.GetLastWriteTime()方法(带示例)

📅  最后修改于: 2021-05-29 15:40:00             🧑  作者: Mango

File.GetLastWriteTime(String)是一个内置的File类方法,该方法用于返回指定文件或目录的最后写入日期和时间。
句法:

public static DateTime GetLastWriteTime (string path);

参数:该函数接受如下所示的参数:

例外情况:

  • UnauthorizedAccessException:调用者没有所需的权限。
  • ArgumentException:路径是长度为零的字符串,仅包含空格,或者由InvalidPathChars定义的一个或多个无效字符。
  • ArgumentNullException:路径为null。
  • PathTooLongException:给定的路径,文件名或两者都超过了系统定义的最大长度。
  • NotSupportedException:路径格式无效。

返回值:返回指定文件或目录的最后写入日期和时间。
下面是说明File.GetLastWriteTime(String)方法的程序。
程序1:在运行下面的代码之前,将创建一个文件file.txt ,其内容如下所示:

file.txt

C#
// C# program to illustrate the usage
// of File.GetLastWriteTime(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
  
        // Calling GetLastWriteTime() function
        DateTime dt = File.GetLastWriteTime(myfile);
  
        // Getting the last write time
        Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}


C#
// C# program to illustrate the usage
// of File.GetLastWriteTime(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
  
        // Setting the date
        File.SetLastWriteTime(myfile, new DateTime(2020, 4, 3));
  
        // Calling GetLastWriteTime() function
        DateTime dt = File.GetLastWriteTime(myfile);
  
        // Getting the last write time
        Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}


执行中:

The last write time for this file was 4/19/2020 4:43:24 AM.

程序2:在运行下面的代码之前,创建了一个文件,如下所示:

file.txt

C#

// C# program to illustrate the usage
// of File.GetLastWriteTime(String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
  
        // Setting the date
        File.SetLastWriteTime(myfile, new DateTime(2020, 4, 3));
  
        // Calling GetLastWriteTime() function
        DateTime dt = File.GetLastWriteTime(myfile);
  
        // Getting the last write time
        Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}

执行中:

The last write time for this file was 4/3/2020 12:00:00 AM.