Michael Bernhard
Michael Bernhard

Reputation: 31

c# File.Exists gets wrong result when network connection has been lost

I have to check a file on a mapped network drive.

f.e. P:\myFolder\myFile.dat

FileInfo fi = new FileInfo(myfile);
if (fi.Exists)
{

    // Exists does not work if the network was interrupted.
    // For whatever reason
    // So now Try ... Catch, the FileInfo constructor can actually be omitted!
    try
    {
        FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(myfile);
        
    }
    catch (FileNotFoundException ex)
    {
        this.Version = new Version("1.0.0");
    }
}
else
{
    this.Version = new Version("1.0.0");
}

It all works fine - until I unplug my network cable. The FileInfo still thinks the file exists.

Why ?

Upvotes: 1

Views: 216

Answers (2)

Rand Random
Rand Random

Reputation: 7440

The documentation states your described behaviour:

When the properties are first retrieved, FileInfo calls the Refresh method and caches information about the file. On subsequent calls, you must call Refresh to get the latest copy of the information.

https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo

Upvotes: 1

Michael Bernhard
Michael Bernhard

Reputation: 31

fi.Refresh(); worked !

@Sommmen File.Exists(myfile) didn't work too. It had the same problems like the FileInfo

Upvotes: 0

Related Questions