FileInfo.MoveTo不更新FileInfo.Exists

时间:2017-11-08 17:39:29

标签: c# file

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

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
        }

有没有办法flush文件系统,或update FileInfo对象?

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

这是否意味着在更改文件系统后,相关的FileInfo对象只是显而易见无效?

1 个答案:

答案 0 :(得分:2)

import CoreLocation import UIKit class ViewController: UIViewController, CLLocationManagerDelegate { let manager = CLLocationManager() override func viewDidLoad() { manager.delegate = self manager.requestLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { print("Found user's location: \(location)") } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } } 是一个实例属性;它是在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