简体   繁体   中英

How to combine file absolute and relative uri or path?

What I want to implement is a combining function that takes one absolute path/uri and one relative path/uri and returns the two combined. For instance, consider these two paths:

var root = "c:\src";
var images = "/images/logo.png" ;
var combined = Combine (root, images); // Either 'c:/src/images/logo.png' or 'c:\src\images\logo.png' is acceptable

I want to avoid manually manipulating/intercepting forward and backward slashes and I want to stick to.Net built-in functionalities. I tried Uri and Path.Combine but no luck. The biggest problem is that the images starts with a forwarding slash, still I guess there must be a way to tell.Net to treat it as relative to the absolute path.

I'm not aware of any built-in functionality to do this in the way you want to.

With that in mind, it seems like you should just be able to remove the leading slash:

var root = "c:\\src";
var sourceOfImages = "/images/logo.png";
var images = sourceOfImages.TrimStart('/', '\\');
var combined = Path.Combine(root, images);

Now this does lead to the output having flashes in differing formats:

c:\src\images/logo.png

I would suggest using string Replace to resolve this:

var combined = Path.Combine(root, images).Replace("/", "\\"); // or .Replace("\\", "/");

This outputs the path as we would expect:

c:\src\images\logo.png

Try it online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM