Windows路径中多个反斜杠的后果(如果有)? [英] What are the consequences, if any, of multiple backslashes in Windows paths?

查看:393
本文介绍了Windows路径中多个反斜杠的后果(如果有)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我经常有在app.config文件中配置的文件名和/或路径。通常是这样的:

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"];

现在,以上代码的结果将给出的日志文件路径C:\Logs\MyLogFile.txt ,但是,如果最终用户在配置文件中将日志文件目录指定为 C:\Logs\ 带有尾部反斜杠,我的代码导致实际路径为 C:\Logs\\MyLogFile.txt ,目录之间有双反斜杠

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.

根据我的经验,这在实践中效果很好。实际上,甚至放到命令提示符下并执行 cd c:\\\windows\\\ 也可以在实践中。

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.

我的问题是,拥有这样的路径会带来什么后果?我不希望在生产代码中使用此功能,如果它没有记录,并且将来可能会在新版本的Windows中被破坏。

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.

推荐答案

据我所知,没有任何后果,而且在以后的版本中也不太可能被打破,因为很多人会和您一样。

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.

但是,在C#中组合路径的正确方法是使用 Path.Combine ,它将为您删除所有多余的反斜杠:

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"]);

这篇关于Windows路径中多个反斜杠的后果(如果有)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆