Roland
Roland

Reputation: 5234

FileInfo.MoveTo does not update FileInfo.Exists

I am moving some file around but noticed that FileInfo.Exists does not really work. In the example below, after moving the file from "foo" to "bar", both FileInfo objects seem to Exist. In other runs, I have seen both Exists to be false.

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
        }

Is there a way to flush the file system, or update the FileInfo objects?

Using the File.Exists method works correctly, no wonder, because it probes the file system after the move.

Does this mean that after a change to the file system, the related FileInfo objects are just plain invalid?

Upvotes: 3

Views: 1442

Answers (1)

Dour High Arch
Dour High Arch

Reputation: 21712

FileInfo.Exists is an instance property; it is created when your FileInfo is instatiated; i.e. when you call FileInfo FI_New = new FileInfo(NewFileName). If NewFileName does not exist and you later create it, FI.Exists will not change. Think about it; if you call:

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

Do you think fileExists changes from False to True at the end of that code? Do you think fi.Exists changes? They don't.

FileInfo.Refresh() is a method that updates the instance properties, including Exists. Or you could call new FileInfo() again.

Upvotes: 5

Related Questions