Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

c# - Why does Path.Combine produce this result with a relative path?

To my surprise, this code does not produce expected results:

var basePath = @"\serverBaseFolder";
var relativePath = @"MyRelativeFolder";

var combinedPath = Path.Combine(basePath, relativePath);

The result is MyRelativeFolder instead of the expected \serverBaseFolderMyRelativeFolder.

Why is this? What's the best way to combine relative paths that may or may not have a slash in them?

EDIT: I'm aware that I can just do string manipulation on relativePath to detect and remove a starting slash. Is there a safer way of doing this (I thought Path.Combine was supposed to be the safe way) that will account for backslashes and frontslashes?

question from:https://stackoverflow.com/questions/5748032/why-does-path-combine-produce-this-result-with-a-relative-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Drop the leading slash on relativePath and it should work.

The reason why this happens is that Path.Combine is interpreting relativePath as a rooted (absolute) path because, in this case, it begins with a . You can check if a path is relative or rooted by using Path.IsRooted().

From the doc:

If the one of the subsequent paths is an absolute path, then the combine operation resets starting with that absolute path, discarding all previous combined paths.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...