从获取绝对名称C#中的URI / URL的父名称 [英] Getting the parent name of a URI/URL from absolute name C#
本文介绍了从获取绝对名称C#中的URI / URL的父名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个绝对URI / URL,我希望得到不包含叶部分的URI / URL。例如:给定 http://foo.com/bar/baz.html ,我应该得到的http://foo.com/bar/ 。
这是我能想出的代码似乎有点长,所以我不知道是否有更好的办法。
静态字符串GetParentUriString(URI URI)
{
StringBuilder的parentName =新的StringBuilder();
//附加方案:HTTP,FTP等
parentName.Append(uri.Scheme);
// Appned的://的HTTP后,FTP等
parentName.Append(://);
//附加主机名www.foo.com
parentName.Append(uri.Host);
//附加每段除了最后一个。最后一个是
//叶,我们会忽略它。
的for(int i = 0; I< uri.Segments.Length - 1;我++)
{
parentName.Append(uri.Segments [I]);
}
返回parentName.ToString();
}
有人会使用该函数是这样的:
静态无效的主要(字串[] args)
{
乌里URI =新的URI(http://foo.com/酒吧/ baz.html);
//应该返回http://foo.com/bar/
串parentName = GetParentUriString(URI);
}
谢谢,
罗希特
< DIV CLASS =h2_lin>解决方案
这是最短的,我可以想出:
静态字符串GetParentUriString(URI URI)
{
返回uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last()长。);
}
如果你想使用最后一个()方法中,你将不得不包括System.Linq的。
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/.
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
解决方案
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.
这篇关于从获取绝对名称C#中的URI / URL的父名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文