What are the consequences, if any, of multiple backslashes in Windows paths?

匆匆过客 提交于 2019-12-31 01:49:09

问题


In my programs I frequently have file names and/or paths that are configured in my app.config file. This will usually be something like:

<add key="LogFileDirectory" value="C:\Logs" />
<add key="SaveLogFileTo" value="MyLogFile.txt" />

In my actual application code, I'll frequently concatenate these together with code similar to this:

var logFile = ConfigurationManager.AppSettings["LogFileDirectory"]
+ @"\" +
ConfigurationManager.AppSettings["SaveLogFileTo"];

Now, the result of the above code would give a log file path of C:\Logs\MyLogFile.txt, however, if the end-user specifies the log file directory in the configuration file as C:\Logs\ with a trailing backslash, my code results in an actual path of C:\Logs\\MyLogFile.txt with a double backslash between the directory and the file.

In my experience, this works just fine in practice. As a matter of fact, even dropping to a command prompt and executing cd c:\\\\\\windows\\\ works in practice.

My question is, what, if any, are the consequences of having paths like this? I don't want to be using this "feature" in production code if it is something that is undocumented and subject to be broken at some point in the future with a new release of Windows.


回答1:


There are no consequences that I know of, and it's not likely to be broken in future versions, because a lot of people will be doing the same as you.

However, the correct way to combine paths in C# is to use Path.Combine, which will remove any extra backslashes for you:

var logFile = Path.Combine(
    ConfigurationManager.AppSettings["LogFileDirectory"],
    ConfigurationManager.AppSettings["SaveLogFileTo"]);


来源:https://stackoverflow.com/questions/30177768/what-are-the-consequences-if-any-of-multiple-backslashes-in-windows-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!