FileInfo Exists lies! Or not?

I’ve recently wrote a code that basically looks like that:

FileInfo GetFile()
{
    var info = new FileInfo(path_to_not_yet_created_file);
    
    var someObj = new SomeObj();

    // ... Logic gathering/preparing various pieces of data ...

    someObj.SaveToFile(info);

    return info;
}

void foo()
{
    FileInfo file = GetFile();
    
    // Defensive programming ftw!
    Debug.Assert(file.Exists);
    
    // ... More code ...
}

Seems reasonable.

  1. Create FileInfo to some file to which you gonna save your result.
  2. Do some computations.
  3. Write the result to a new file pointed by FileInfo.
  4. Validate that the file was created using Exists property.

But it doesn’t work. Exists always returns false. The file is definitely there, process have adequate access rights, the path matches … even your dog can see the file. Madness!

After playing around for some time I learned one simple truth: FileInfo isn’t automatically refreshed and won’t reflect the current state of the file when querying its state. In Debug.Assert(file.Exists) Exists will always return false as at the point of creation (var info = new FileInfo(path_to_not_yet_created_file)) the file wasn’t existing.

I will stick with plain ol’ string for now, and remember not to use FileInfo so much. Hope that saves you some time.

Advertisements

Tags: , ,

One Response to “FileInfo Exists lies! Or not?”

  1. Radio Raheem Says:

    FWIW you can just do file.Refresh() before testing file.Exists() – then you will get the anticipated result.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: