gpt4 book ai didi

c# - FileInfo.MoveTo 不更新 FileInfo.Exists

转载 作者:行者123 更新时间:2023-11-30 21:37:30 24 4
gpt4 key购买 nike

我正在四处移动一些文件,但发现 FileInfo.Exists 并不真正起作用。在下面的示例中,将文件从“foo”移动到“bar”后,两个 FileInfo 对象似乎都是 Exist。在其他运行中,我发现这两个 Exists 都是假的。

using System.IO;//File, FileInfo

public static void TestMoveTo()
{
// create file 1
string FileName = @"d:\temp\foo.txt";
File.WriteAllText(FileName, "Test file\n");
FileInfo FI_Test = new FileInfo(FileName);
// move to file 2
string NewFileName = @"d:\temp\bar.txt";
if (File.Exists(NewFileName))
File.Delete(NewFileName);
FileInfo FI_New = new FileInfo(NewFileName);
FI_Test.MoveTo(FI_New.FullName);
// test
bool OldExists = FI_Test.Exists;
bool NewExists = FI_New.Exists;
// use File.Exists
bool OldExists2 = File.Exists(FileName);
bool NewExists2 = File.Exists(NewFileName);
return;//debug breakpoint
}

有没有办法刷新文件系统,或者更新 FileInfo 对象?

使用 File.Exists 方法可以正常工作,难怪,因为它会在移动后探测文件系统。

这是否意味着在更改文件系统后,相关的 FileInfo 对象就完全无效了?

最佳答案

FileInfo.Exists 是一个实例属性;它是在您的 FileInfo 实例化时创建的;即当您调用 FileInfo FI_New = new FileInfo(NewFileName) 时。如果 NewFileName 不存在并且您稍后创建了它,则 FI.Exists 不会更改。想一想;如果你打电话:

var noSuchFile = @"c:\this file does not exist";
File.Delete(noSuchFile); // just to be sure...
var fileExists = File.Exists();
var fi = new FileInfo(noSuchFile);
File.Create(noSuchFile);

您认为 fileExists 在该代码末尾从 False 变为 True 吗?你认为 fi.Exists 有变化吗?他们没有。

FileInfo.Refresh() 是一种更新实例属性的方法,包括 Exists。或者您可以再次调用 new FileInfo()

关于c# - FileInfo.MoveTo 不更新 FileInfo.Exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47186245/

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