简体   繁体   English

如何结合文件绝对和相对uri或路径?

[英]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.我想要实现的是一个组合 function ,它采用一个绝对路径/uri 和一个相对路径/uri 并返回两者的组合。 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.我想避免手动操作/拦截正斜杠和反斜杠,并且我想坚持使用 .Net 内置功能。 I tried Uri and Path.Combine but no luck.我尝试了UriPath.Combine但没有运气。 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.最大的问题是images以正斜杠开头,但我想必须有一种方法告诉.Net 将其视为相对于绝对路径。

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:现在这确实导致 output 具有不同格式的闪存:

c:\src\images/logo.png c:\src\images/logo.png

I would suggest using string Replace to resolve this:我建议使用字符串Replace来解决这个问题:

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在线尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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