简体   繁体   中英

How to detect that a file does not exist?

A 3rd party library errors out when the file paths are invalid. We attempted to handle this case using File.Exists() thinking that it would return false when the file path contains invalid characters, but it returns true .

This is strange (see the extra spaces and period)

    string wrong = "myfolder1\\myfolder2\\myfile.txt      .";
    bool x = File.Exists(wrong);

Is there a way to clean up the file path?

new FileInfo(wrong).Name does not clean it up.

Our main purpose is to reliably determine if the file path is valid before sending it into the 3rd party library. I almost feel stupid asking this question because I think that File.Exists() ought to be doing this.

(We're on .NET 4.0)

The windows API trims trailing periods and spaces from filenames, if it was anything other than a period it would have worked.

See this msdn article for more info.

Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a period as the first character of a name. For example, ".temp".


I don't know if it will work but you may be able to bypass the shell by using the \\\\?\\ prefix, try File.Exists(@"\\\\?\\C:\\myfolder1\\myfolder2\\myfile.txt ."); and see if that works (I can't test this moment right now, if it does not let me know and I will remove this section.)

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