简体   繁体   中英

File.Exist returning true when path has multiple backslashes

I have an application that accepts user input and does stuff to files. The users select a file and it might move it, delete it, rename it, ftp it etc. The application uses a hash table to store recently used files and their paths.

The main problem I am looking into now is one of the add-ins is saving the path incorrectly, it is saving it as such: C:\\David\\\\File.txt

The part of the application that deals with file io tries to ensure the file exists prior to doing stuff with a File.Exists(path) call. This call is returning true even for the above example. Can anyone explain why this might be?

The issue I am facing is, beyond one module saving the path incorrectly, certain modules that interact with the file are accepting that incorrect path and working fine while others see it and crash. Although currently I am going to fix this by getting the path saved correctly, I'd like to understand what is going on here.

You have a false premise: that C:\\David\\\\File.txt is an invalid path. Multiple backslashes are accepted fine in Windows. Try notepad C:\\David\\\\File.txt in a command prompt as an experiment--it should work.

For more info, see this other SO q/a that reaffirms this. Any number of backslashes are fine, and this can be used as a "easy" way to combine paths without worrying about the number of backslashes. For example, the user can provide C:\\David or C:\\David\\ and you can add \\test.txt without worrying which input the user provided. However, Path.Combine is the real way to do this in C#.

Edit: To remove your extra \\ 's easily before passing the path into the other program, try splitting the path into the drive and folder names and combining it back together into a path. Like this:

string path = Path.Combine(pathWithManyBackslashes.Split('\\'));

Because Split doesn't create new entries when the delimiter repeats, you get rid of them. For example, C:\\David\\\\File.txt => [ C: , David , File.txt ].

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