【问题标题】:Getting the parent name of a URI/URL from absolute name C#从绝对名称 C# 获取 URI/URL 的父名称
【发布时间】:2010-10-05 08:17:12
【问题描述】:

给定一个绝对 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);                        
    }

谢谢, 罗希特

【问题讨论】:

    标签: c# uri


    【解决方案1】:

    这是我能想到的最短的:

    static string GetParentUriString(Uri uri)
    {
        return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
    }
    

    如果要使用 Last() 方法,则必须包含 System.Linq。

    【讨论】:

    • 是的,但是如果 URL 有重复的字符串,这不会导致问题:foo.com/bar/baz/bar
    • 警告:这会忽略查询字符串。
    • @Brian 是正确的,但要澄清一下:Martin 的解决方案在存在查询字符串时有效,但这被排除在返回值之外。
    • 不,当存在查询字符串时它不能正常工作。调用GetParentUriString(new Uri("http://foo.com/bar/baz.html?q=val")) 将返回http://foo.com/bar/baz.ht
    • 这对于C:\sites\041323_KaiTakSportsPark 形式的路径表现不佳,该路径被剪切为C:\sites\041323_KThis answer 尤其是 its related comment 更简单且通用
    【解决方案2】:

    又快又脏

    int pos = uriString.LastIndexOf('/');
    if (pos > 0) { uriString = uriString.Substring(0, pos); } 
    

    【讨论】:

    • 仅供参考...在某些情况下这可能会中断...如果查询字符串中存在一个非常合法的未编码 URI
    • 谢谢史蒂夫。对我来说,它证明了一个观点,即永远不应该对复杂格式(例如 URI 或文件路径)使用裸字符串或正则表达式操作:)
    【解决方案3】:

    必须有一种更简单的方法来使用内置的 uri 方法,但这是我对 @unknown (yahoo) 建议的看法。
    在这个版本中,您不需要 System.Linq,它还可以处理带有查询字符串的 URI:

    private static string GetParentUriString(Uri uri)
    {
        return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length -1].Length - uri.Query.Length);
    }
    

    【讨论】:

      【解决方案4】:

      我找到的最短路径:

      static Uri GetParent(Uri uri) {
          return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
      }
      

      【讨论】:

        【解决方案5】:

        你试过了吗?看起来很简单。

        Uri parent = new Uri(uri, "..");
        

        【讨论】:

        • 有点不正确。正如你现在所拥有的,只有当 uri 是一个目录时它才是正确的。如果 uri 是一个文件(如原帖所示),那么正确的方法是Uri parent = new Uri(uri, ".");
        【解决方案6】:
        new Uri(uri.AbsoluteUri + "/../")
        

        【讨论】:

          【解决方案7】:

          PapyRef 的回答不正确,UriPartial.Path 包含文件名。

          new Uri(uri, ".").ToString()
          

          似乎是所请求功能的最简洁/最简单的实现。

          【讨论】:

          • 我发现它只有在资源是文件时才有效。如果它是一个以/ 结尾的 URL,它不会删除最后一段。
          【解决方案8】:

          获取url的分段

          url="http://localhost:9572/School/Common/Admin/Default.aspx"
          
          Dim name() As String = HttpContext.Current.Request.Url.Segments
          
          now simply using for loop or by index, get parent directory name
          
          code = name(2).Remove(name(2).IndexOf("/"))
          

          这返回给我,“普通”

          【讨论】:

            【解决方案9】:

            我在这里阅读了很多答案,但没有找到我喜欢的答案,因为它们在某些情况下会中断。

            所以,我正在使用这个:

            public Uri GetParentUri(Uri uri) {
                var withoutQuery = new Uri(uri.GetComponents(UriComponents.Scheme |
                                                             UriComponents.UserInfo |
                                                             UriComponents.Host |
                                                             UriComponents.Port |
                                                             UriComponents.Path, UriFormat.UriEscaped));
                var trimmed = new Uri(withoutQuery.AbsoluteUri.TrimEnd('/'));
                var result = new Uri(trimmed, ".");
                return result;
            }
            

            注意:它会故意删除查询和片段。

            【讨论】:

              【解决方案10】:

              以为我会插话;尽管已经将近 10 年了,但随着云的出现,获取父 Uri 是一种相当普遍(并且 IMO 更有价值)的场景,因此在这里结合一些答案,您只需使用(扩展的)Uri 语义:

              public static Uri Parent(this Uri uri)
              {
                  return new Uri(uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - uri.Query.Length).TrimEnd('/'));
              }
              
              var source = new Uri("https://foo.azure.com/bar/source/baz.html?q=1");
              
              var parent = source.Parent();         // https://foo.azure.com/bar/source
              var folder = parent.Segments.Last();  // source
              

              我不能说我已经测试了所有场景,所以建议谨慎。

              【讨论】:

                猜你喜欢
                • 2019-12-17
                • 1970-01-01
                • 2018-06-26
                • 1970-01-01
                • 2012-07-02
                • 1970-01-01
                • 2014-04-18
                • 2018-06-09
                • 2015-02-24
                相关资源
                最近更新 更多