File.Exist returning true when path has multiple backslashes

后端 未结 1 1824
耶瑟儿~
耶瑟儿~ 2021-01-28 13:16

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 has

相关标签:
1条回答
  • 2021-01-28 14:11

    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].

    0 讨论(0)
提交回复
热议问题