File.Copy() 或 Directory.CreateDirectory() 方法的路径变量中的额外斜杠
当我使用某些 System.IO
方法,并且“不小心”在路径变量中添加了额外的斜杠 (\
) 时,似乎没有发生任何特殊情况。没有错误或警告,并且代码的工作方式就像存在适量的斜杠一样。
示例:
Directory.CreateDirectory(@"C:\Users\Public\Documents\\test");
File.Copy(@"C:\Users\Public\\Documents\test.txt", @"C:\Users\\Public\Documents\test\test.txt", true);
所以我想知道,如果上面的代码有时有额外的斜杠,是否有潜在的危险,或者在任何情况下都没有一点关系?
When I use some System.IO
methods, and "accidentally" put extra slashes (\
) in the path variables, nothing special seems to happen. No errors or warnings, and the code works as if just the right amount of slashes were present.
Example:
Directory.CreateDirectory(@"C:\Users\Public\Documents\\test");
File.Copy(@"C:\Users\Public\\Documents\test.txt", @"C:\Users\\Public\Documents\test\test.txt", true);
So I'm wondering, is it potentially dangerous if the code above had extra slashes sometimes, or would it not matter one iota under any circumstances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Windows 对此相当有弹性,尚未注意到问题。
查看此线程中的代码片段。请注意 _ACP_INCLUDE 环境变量的值。您必须向右滚动才能看到:
Afaik,很多装有 VS2008 的机器都有这个坏路径,我的当然也有。然而,当您解析路径字符串时,它肯定会导致您自己的代码出错。
Windows is quite resilient to this, haven't noticed a problem yet.
Take a look at the snippet in this thread. Note the value of the _ACP_INCLUDE environment variable. You have to scroll to the right to see:
Afaik, a lot of machines that have VS2008 have this bad path, mine certainly does. Nevertheless, it certainly can trip up your own code when you parse path strings.
Windows似乎并不介意,但为什么不做出优雅的代码呢?
Windows does not seem to mind, but why not make elegant code?
我非常确定 Windows 在使用路径结构之前会对其进行“标准化”。但是,为了安全起见,最好使用以下方式组合路径:
而不是连接两个字符串。
I'm pretty sure Windows "normalizes" the path structure before using it. To be safe, however, it is best to combine paths using:
instead of concatenating two strings.
您应该了解的情况,
http://msdn。 microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
我不知道 .NET 如何包装这个 api。我想汉斯·帕桑特可能对此很了解。 :)
The case you should know,
http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
I have no idea how .NET wraps this api. I guess Hans Passant might knows well about this. :)