2017-02-10 71 views
1

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

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(); 

回答

5

尝试使用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; 
    } 
}