为什么Path.Combine不能正确串接开头Path.DirectorySeparatorChar文件名? [英] Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

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

问题描述

即时窗口的Visual Studio中:

From the Immediate Window in Visual Studio:

? System.IO.Path.Combine(@"C:\test",@"test")
"C:\\test\\test"
? System.IO.Path.Combine(@"C:\test",@"\test")
"\\test"

看起来他们都应该是相同的。

It seems that they should both be the same.

旧FileSystemObject.BuildPath()并没有以这种方式工作...

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.

<一个href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx">System.IO.Path.Combine

如果PATH2包含一个绝对路径,此方法将返回路径2。

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

下面是从.NET源的实际相结合的方法。你可以看到,它调用<一个href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745">CombineNoChecks,然后调用<一个href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d">IsPathRooted在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.

我不知道理由是什么。我想解决方案是从所述第二路径的开始剥离(或修剪)DirectorySeparatorChar;也许写下自己的结合方法,做了,然后调用Path.Combine()。

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天全站免登陆