文件存在 c# visual studio 2017

file Exists c# visual studio 2017

无法找到该文件和该路径中的文件。

FileInfo file = new FileInfo(@"\10.125.16.22\Facturas Electronicas\Factura EMP000098.pdf");
if (file.Exists)
{
    EventLog.WriteEntry("encontro los adjuntos de la factura " + nrodocumento);
    File.Copy(ruta, @"C:\Factura\" + file.Name + ".pdf", true);
    cantidad++;
}
else
{
    EventLog.WriteEntry("no existe el adjunto " + ruta);
}

当它达到 if (file.Exists) 时,结果是 False。我使用的项目类型是 Visual Studio 服务项目。

配置中的服务 windows Account LocalSystem 我必须更改它吗?

如果不是"Local System"我应该处理哪个?

the service windows in the configuration I have Account LocalSystem I must change it ?

是的,你必须改变这个。 LocalSystem 帐户对 10.125.16.22 的计算机没有任何权限。 即使是同一台计算机也是如此! UNC 路径将强制进行网络访问,LocalSystem 不会通过网络提供任何凭据。因此 File.Exists() 总是 return false,无论文件的实际状态如何。这在 the Remarks section of the documentation.

的末尾进行了介绍

The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

此外,它是 almost always poor practice to use File.Exists() in the first place。相反,只需尝试复制文件并在失败时处理异常。无论如何您都需要这样做,因为有 很多 文件复制失败的原因可能与现有文件无关。这也是 更快 ,因为尽管异常处理可能很慢,但它通常仍然比 [=14] 调用的额外 disk/network I/O 操作集快得多=] 检查。