Path.Combine很方便,但是.NET框架中是否有类似的URL函数?

我正在寻找这样的语法:

Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")

这将返回:

"http://MyUrl.com/Images/Image.jpg"


当前回答

这是我的方法,我也会自己使用:

public static string UrlCombine(string part1, string part2)
{
    string newPart1 = string.Empty;
    string newPart2 = string.Empty;
    string seperator = "/";

    // If either part1 or part 2 is empty,
    // we don't need to combine with seperator
    if (string.IsNullOrEmpty(part1) || string.IsNullOrEmpty(part2))
    {
        seperator = string.Empty;
    }

    // If part1 is not empty,
    // remove '/' at last
    if (!string.IsNullOrEmpty(part1))
    {
        newPart1 = part1.TrimEnd('/');
    }

    // If part2 is not empty,
    // remove '/' at first
    if (!string.IsNullOrEmpty(part2))
    {
        newPart2 = part2.TrimStart('/');
    }

    // Now finally combine
    return string.Format("{0}{1}{2}", newPart1, seperator, newPart2);
}

其他回答

我只是拼凑了一个小的扩展方法:

public static string UriCombine (this string val, string append)
        {
            if (String.IsNullOrEmpty(val)) return append;
            if (String.IsNullOrEmpty(append)) return val;
            return val.TrimEnd('/') + "/" + append.TrimStart('/');
        }

它可以这样使用:

"www.example.com/".UriCombine("/images").UriCombine("first.jpeg");

您使用Uri.TryCreate(…):

Uri result = null;

if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
    Console.WriteLine(result);
}

将返回:

http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx

如果任何人正在寻找一个单行,并且只想在不创建新方法或引用新库的情况下连接路径的一部分,或者构造URI值并将其转换为字符串,那么。。。

string urlToImage = String.Join("/", "websiteUrl", "folder1", "folder2", "folder3", "item");

这很基本,但我看不出你还需要什么。如果你害怕“/”加倍,那么你可以简单地在后面做一个替换(“//”,“/”)。如果您害怕替换“https://”中的双引号“//”,那么请执行一次连接,替换双引号“/”,然后加入网站url(但是我很确定大多数浏览器会自动将前面带有“https://的内容转换为正确格式)。这看起来像:

string urlToImage = String.Join("/","websiteUrl", String.Join("/", "folder1", "folder2", "folder3", "item").Replace("//","/"));

这里有很多答案可以解决以上所有问题,但在我的情况下,我只需要在一个地方使用一次,不需要过度依赖它。此外,很容易看到这里发生了什么。

参见:https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8

我的通用解决方案:

public static string Combine(params string[] uriParts)
{
    string uri = string.Empty;
    if (uriParts != null && uriParts.Any())
    {
        char[] trims = new char[] { '\\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);

        for (int i = 1; i < uriParts.Length; i++)
        {
            uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
    }

    return uri;
}

我必须指出,Path.Combine似乎也能直接实现这一点,至少在.NET 4上是如此。