简体   繁体   中英

file Exists c# visual studio 2017

Can not find the file and the file if it is in that route.

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

when it reaches if (file.Exists) the result is False . The type of project that I am using is Visual Studio Service Project.

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

if it is not "Local System" which should I handle?

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

Yes, you must change this. The LocalSystem account won't have any permissions for the computer at 10.125.16.22 . This is true even if it's the same computer! The UNC path will force a network access, and LocalSystem won't present any credentials over the network. Therefore File.Exists() will always return false , no matter the actual state of the file. This is covered at the end of 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.

Additionally, it's almost always poor practice to use File.Exists() in the first place. Instead, just try to copy the file and handle the exception if it fails. You need to do this anyway, because there are lots of reasons a file copy might fail that have nothing to do with the file existing. This is also faster , because as slow as exception handling can be it's still usually much faster than the extra set of disk/network I/O operations invoked by the File.Exists() check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM