File.SetLastWriteTime(String)是一個內置的File類方法,用於設置指定文件的最後寫入日期和時間。
用法:
public static void SetLastWriteTime (string path, DateTime lastWriteTime);
參數:此函數接受兩個參數,如下所示:
- path: This is the specified file for which to set the date and time information.
- lastWriteTime: This is the specified local last write date and time of the path.
異常:
- ArgumentException:路徑為長度為零的字符串,僅包含空格,或者由InvalidPathChars定義的一個或多個無效字符。
- ArgumentNullException:路徑為空。
- PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
- FileNotFoundException:找不到指定的路徑。
- UnauthorizedAccessException:調用者沒有所需的權限。
- NotSupportedException:路徑格式無效。
- ArgumentOutOfRangeException:lastWriteTime指定一個超出此操作允許的日期或時間範圍的值。
下麵是說明File.SetLastWriteTime(String,DateTime)方法的程序。
程序1:在運行下麵的代碼之前,將創建一個文件file.txt,其內容如下所示:
// C# program to illustrate the usage
// of File.SetLastWriteTime() method
// Using System and System.IO namespaces
using System;
using System.IO;
class GFG {
public static void Main()
{
// Specifing a file
string myfile = @"file.txt";
// Calling the SetLastWriteTime() function
// to set last written date and time
File.SetLastWriteTime(myfile, new DateTime(2020,
5, 4, 4, 5, 7));
// Getting the last written date and time
// of the file
DateTime dt = File.GetLastWriteTime(myfile);
Console.WriteLine("The last written date and "+
"time for this file was {0}.", dt);
}
}
輸出:
The last written date and time for this file was 5/4/2020 4:05:07 AM.
程序2:最初,沒有創建文件。在代碼下方,其自身創建文件file.txt並打印最後寫入的日期和時間。
// C# program to illustrate the usage
// of File.SetLastWriteTime() method
// Using System and System.IO namespaces
using System;
using System.IO;
class GFG {
public static void Main()
{
// Specifing a file
string path = @"file.txt";
// Checking the existance of the file
if (!File.Exists(path)) {
File.Create(path);
}
// Calling the SetLastWriteTime() function
// to set last written date and time
File.SetLastWriteTime(path, new DateTime(2019,
5, 4, 4, 5, 7));
// Getting the last written date and time
// of the specified file
DateTime dt = File.GetLastWriteTime(path);
Console.WriteLine("The last written date and "+
"time for this file was {0}.", dt);
}
}
執行中:
The last written date and time for this file was 5/4/2019 4:05:07 AM.
相關用法
- C# MathF.Cos()用法及代碼示例
- C# MathF.Sin()用法及代碼示例
- C# MathF.Min()用法及代碼示例
- C# MathF.Max()用法及代碼示例
- C# MathF.Log()用法及代碼示例
- C# MathF.Abs()用法及代碼示例
- C# MathF.Exp()用法及代碼示例
- C# MathF.Pow()用法及代碼示例
- C# MathF.Tan()用法及代碼示例
- C# Int16.Equals用法及代碼示例
- C# SByte.Equals用法及代碼示例
- C# UInt16.GetHashCode用法及代碼示例
- C# SByte.GetTypeCode用法及代碼示例
- C# SByte.GetHashCode用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.SetLastWriteTime() Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。