gpt4 book ai didi

.net - .NET 的 FileInfo.Length 属性是惰性的吗?

转载 作者:行者123 更新时间:2023-12-02 08:59:27 24 4
gpt4 key购买 nike

以下代码生成 FileNotFoundException(使用 .NET 2.0):

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace LazyFileInfoTest
{
class Program
{
static void Main(string[] args)
{
File.WriteAllText("Test.txt", "Hello World!");

DirectoryInfo di = new DirectoryInfo(".");

FileInfo[] files = di.GetFiles();

File.Delete("Test.txt");

foreach (FileInfo fi in files)
{

Console.WriteLine(string.Format("{0} Last Modified: {1}", fi.Name, fi.LastWriteTime));
Console.WriteLine(string.Format("{0} Last Modified: {1}", fi.Name, fi.LastAccessTime));
//Exception when we reach test.txt
Console.WriteLine(string.Format("{0} length is: {1}", fi.Name, fi.Length));
}
}
}
}

看起来 Length 属性是惰性的。有什么理由吗?这似乎是不一致的,因为其他属性并非如此。 (有关反例,请参阅 .NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong。)

谢谢。

最佳答案

来自 FileInfo.Length 的文档:

When first called, FileInfo calls Refresh and caches information on the file. On subsequent calls, you must call Refresh to get the latest copy of the information.

这似乎是正确的 - 看起来其他属性很渴望,这违反了他们的文档。

关于.net - .NET 的 FileInfo.Length 属性是惰性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2418259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com