从绝对名称获取URI/URL的父级名称 C#

21

给定一个绝对URI/URL,我想获取一个不包含末尾部分的URI/URL。例如:给定 http://foo.com/bar/baz.html ,我应该得到 http://foo.com/bar/

我能想到的代码似乎有点冗长,所以我想知道是否有更好的方法。

static string GetParentUriString(Uri uri)
    {            
        StringBuilder parentName = new StringBuilder();

        // Append the scheme: http, ftp etc.
        parentName.Append(uri.Scheme);            

        // Appned the '://' after the http, ftp etc.
        parentName.Append("://");

        // Append the host name www.foo.com
        parentName.Append(uri.Host);

        // Append each segment except the last one. The last one is the
        // leaf and we will ignore it.
        for (int i = 0; i < uri.Segments.Length - 1; i++)
        {
            parentName.Append(uri.Segments[i]);
        }
        return parentName.ToString();
    }

有人会像这样使用该函数:

  static void Main(string[] args)
    {            
        Uri uri = new Uri("http://foo.com/bar/baz.html");
        // Should return http://foo.com/bar/
        string parentName = GetParentUriString(uri);                        
    }

谢谢,Rohit

11个回答

0

最安全的解决方案,可以正确地处理有/无查询的情况:

public static string GetParentUrl(string sourceUrl)
{
    return GetParentUrl(new Uri(sourceUrl));
}

public static string GetParentUrl(Uri sourceUri)
{
    return GetParentUri(sourceUri).AbsoluteUri;
}

public static Uri GetParentUri(string sourceUrl)
{
    return GetParentUri(new Uri(sourceUrl));
}

public static Uri GetParentUri(Uri sourceUri)
{
    string absolutePath = sourceUri.AbsolutePath.TrimStart('/').TrimEnd('/');
    return new Uri($"{sourceUri.Scheme}://{sourceUri.Host}/{absolutePath}/../");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接