gpt4 book ai didi

c#-4.0 - 文件复制后 FileInfo.Exists 返回 False

转载 作者:行者123 更新时间:2023-12-03 06:22:43 25 4
gpt4 key购买 nike

在下面的代码中,test.txt 在运行之前就存在,而 test2.txt 则不存在。当运行 destFile.Exists 将文件复制到 destFile 的位置后返回 null。是什么原因造成的?我在 msdn 中找不到任何支持正在发生的事情的信息。

    var origFile = new FileInfo(@"C:\Users\user\Desktop\CopyTest\test.txt");
var destFile = new FileInfo(@"C:\Users\user\Desktop\CopyTest\test2.txt");

if (!destFile.Exists && origFile.Exists)
origFile.CopyTo(destFile.FullName);

if (destFile.Exists)
Console.WriteLine("The file was found");

Console.ReadLine();

最佳答案

尝试使用destFile.Refresh();在您访问该特性之前

destFile.Refresh();
if (destFile.Exists)
Console.WriteLine("The file was found");

或者使用静态方法File.Exists :

if (File.Exists(@"C:\Users\user\Desktop\CopyTest\test2.txt"))
Console.WriteLine("The file was found");

FileInfo提供了很多信息,但这是一个快照,将在您第一次访问时初始化,以后不会更新。因此,仅当您需要当前状态并且需要多个信息时才使用它。否则使用 static methods in System.IO.File .

Here您可以看到 Exists 属性的当前实现。您会看到它在您第一次访问它时对其进行初始化,稍后将返回旧状态:

public override bool Exists {
[System.Security.SecuritySafeCritical] // auto-generated
get {
try {
if (_dataInitialised == -1)
Refresh();
if (_dataInitialised != 0) {
// Refresh was unable to initialise the data.
// We should normally be throwing an exception here,
// but Exists is supposed to return true or false.
return false;
}
return (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0;
}
catch
{
return false;
}
}

关于c#-4.0 - 文件复制后 FileInfo.Exists 返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42163905/

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