2017-02-10 29 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; 
    } 
} 
相關問題