在下面的代码中,test.txt在运行之前就存在了,而test2.txt却没有.在将文件复制到destFile的位置后运行destFile.Exists时返回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();
Run Code Online (Sandbox Code Playgroud)
destFile.Refresh();在您进入酒店之前尝试使用
destFile.Refresh();
if (destFile.Exists)
Console.WriteLine("The file was found");
Run Code Online (Sandbox Code Playgroud)
或使用静态方法File.Exists:
if (File.Exists(@"C:\Users\user\Desktop\CopyTest\test2.txt"))
Console.WriteLine("The file was found");
Run Code Online (Sandbox Code Playgroud)
在FileInfo提供了大量的信息,但是这是这将是你第一次访问它并不会在以后更新初始化的快照.因此,只有在需要当前状态且需要多个信息时才使用它.否则使用静态方法System.IO.File.
在这里,您可以看到该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;
}
}
Run Code Online (Sandbox Code Playgroud)