为什么Path.Combine不能正确连接起始于Path.DirectorySeparatorChar的文件名? [英] Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

查看:199
本文介绍了为什么Path.Combine不能正确连接起始于Path.DirectorySeparatorChar的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Visual Studio中的立即窗口

 > Path.Combine(@C:\x,y)
C:\\x\\
> Path.Combine(@C:\x,@\y)
\\

似乎他们应该是一样的。



旧的FileSystemObject.BuildPath()没有这样工作...

解决方案

这是一个哲学问题(可能只有微软才能真正回答),因为它正在完全符合文档说明。



System.IO.Path.Combine



如果path2包含绝对路径,则此方法返回path2。



以下是.NET源的实际组合方法。您可以看到它调用 CombineNoChecks ,然后调用在路径2上 IsPathRooted ,并返回该路径。 / p>

我不知道是什么理由。我想解决方案是从第二个路径的开始剥离(或修剪)DirectorySeparatorChar;可能写你自己的Combine方法,然后调用Path.Combine()。


From the Immediate Window in Visual Studio:

> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"

It seems that they should both be the same.

The old FileSystemObject.BuildPath() didn't work this way...

解决方案

This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.

System.IO.Path.Combine

"If path2 contains an absolute path, this method returns path2."

Here's the actual Combine method from the .NET source. You can see that it calls CombineNoChecks, which then calls IsPathRooted on path2 and returns that path if so.

I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().

这篇关于为什么Path.Combine不能正确连接起始于Path.DirectorySeparatorChar的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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