从绝对名称C#获取URI / URL的父名称
给定一个绝对的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); }
谢谢,罗希特
这是我能想到的最短的:
static string GetParentUriString(Uri uri) { return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length); }
如果要使用Last()方法,则必须包含System.Linq。
你试过这个吗? 看起来很简单。
Uri parent = new Uri(uri, "..");
使用内置的uri方法必须有一个更简单的方法来做到这一点,但这是我对@unknown(雅虎)的建议的转折。
在此版本中,您不需要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); }
又脏又脏
int pos = uriString.LastIndexOf('/'); if (pos > 0) { uriString = uriString.Substring(0, pos); }
我找到的最短路:
static Uri GetParent(Uri uri) { return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/"); }
我在这里阅读了许多答案,但没有找到我喜欢的答案,因为它们在某些情况下会破坏。
所以,我使用这个:
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; }
注意:它会故意删除Query和Fragment。
new Uri(uri.AbsoluteUri + "/../")
获取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("/"))
这让我回归,“共同”
PapyRef的答案不正确, UriPartial.Path
包含文件名。
new Uri(uri, ".").ToString()
似乎是所请求function的最干净/最简单的实现。
以为我会参与其中; 尽管近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
我不能说我已经测试过每一个场景,所以请注意。