从绝对名称 C# 获取 URI/URL 的父名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/510240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the parent name of a URI/URL from absolute name C#
提问by Rohit
Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given http://foo.com/bar/baz.html, I should get http://foo.com/bar/.
给定一个绝对 URI/URL,我想获得一个不包含叶子部分的 URI/URL。例如:给定http://foo.com/bar/baz.html,我应该得到http://foo.com/bar/。
The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.
我能想出的代码似乎有点冗长,所以我想知道是否有更好的方法。
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();
}
One would use the function something like this:
人们会使用这样的函数:
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);
}
Thanks, Rohit
谢谢,罗希特
采纳答案by Martin
This is the shortest I can come up with:
这是我能想到的最短的:
static string GetParentUriString(Uri uri)
{
return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
}
If you want to use the Last() method, you will have to include System.Linq.
如果要使用 Last() 方法,则必须包含 System.Linq。
回答by dbkk
Quick and dirty
又快又脏
int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); }
回答by eft
There must be an easier way to do this with the built in uri methods but here is my twist on @unknown (yahoo)'s suggestion.
In this version you don't need System.Linq
and it also handles URIs with query strings:
必须有一种更简单的方法来使用内置的 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);
}
回答by riel
Shortest way I found:
我发现的最短方法:
static Uri GetParent(Uri uri) {
return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}
回答by trypto
Did you try this? Seems simple enough.
你试过这个吗?看起来很简单。
Uri parent = new Uri(uri, "..");
回答by stung
new Uri(uri.AbsoluteUri + "/../")
回答by Dylan Nicholson
PapyRef's answer is incorrect, UriPartial.Path
includes the filename.
PapyRef 的回答不正确,UriPartial.Path
包括文件名。
new Uri(uri, ".").ToString()
seems to be cleanest/simplest implementation of the function requested.
似乎是所请求功能的最干净/最简单的实现。
回答by Rajesh Londhe
Get segmenation of url
获取 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("/"))
This returns me, "Common"
这使我返回“普通”
回答by Andre Soares
I read many answers here but didn't find one that I liked because they break in some cases.
我在这里阅读了很多答案,但没有找到我喜欢的答案,因为它们在某些情况下会损坏。
So, I am using this:
所以,我正在使用这个:
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;
}
Note:It removes the Query and the Fragment intentionally.
注意:它有意删除了 Query 和 Fragment。
回答by hector-j-rivas
Thought I'd chime in; despite it being almost 10 years, with the advent of the cloud, getting the parent Uri is a fairly common (and IMO more valuable) scenario, so combining some of the answers here you would simply use (extended) Uri semantics:
以为我会插话;尽管已经快 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
I can't say I've tested every scenario, so caution advised.
我不能说我已经测试了所有场景,所以建议谨慎。