网络连接丢失时,c#File.Exists结果错误

时间:2020-08-21 09:10:36

标签: c# networking connection fileinfo

我必须检查映射的网络驱动器上的文件。

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

一切正常-直到拔下网络电缆为止。 FileInfo仍然认为该文件存在。

为什么?

2 个答案:

答案 0 :(得分:1)

文档说明您描述的行为:

首次检索属性时,FileInfo调用Refresh方法并缓存有关文件的信息。在后续通话中,您必须致电刷新以获取最新信息。

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

答案 1 :(得分:0)

fi.Refresh(); worked !

@Sommmen File.Exists(myfile)也不起作用。 它有和FileInfo一样的问题