2009-10-23 41 views

回答

2

没有属性,但它不是太难解析出来:

Uri uri = new Uri("http://www.example.com/mydirectory/myfile.aspx"); 
string[] parts = uri.LocalPath.Split('/'); 
if(parts.Length >= parts.Length - 2){ 
    string directoryName = parts[parts.Length - 2]; 
} 
+2

检查Rubens Farias的答案在下面,因为它比这个好得多。 – bigbearzhu 2015-08-07 04:40:20

0

如果您确定URL的末尾有文件名,则以下代码可以使用。

using System; 
using System.IO; 

Uri u = new Uri(@"http://www.example.com/mydirectory/myfile.aspx?v=1&t=2"); 

//Ensure trailing querystring, hash, etc are removed 
string strUrlCleaned = u.GetLeftPart(UriPartial.Path); 
// Get only filename 
string strFilenamePart = Path.GetFileName(strUrlCleaned); 
// Strip filename off end of the cleaned URL including trailing slash. 
string strUrlPath = strUrlCleaned.Substring(0, strUrlCleaned.Length-strFilenamePart.Length-1); 

MessageBox.Show(strUrlPath); 
// shows: http://www.example.com/mydirectory 

我在URL的查询字符串中添加了一些垃圾,以便在追加参数时证明它仍然有效。

1

简单字符串操作怎么样?

public static Uri GetDirectory(Uri input) { 
    string path = input.GetLeftPart(UriPartial.Path); 
    return new Uri(path.Substring(0, path.LastIndexOf('/'))); 
} 

// ... 
newUri = GetDirectory(new Uri ("http://www.example.com/mydirectory/myfile.aspx")); 
// newUri is now 'http://www.example.com/mydirectory' 
37

试试这个(没有字符串操作):

Uri baseAddress = new Uri("http://www.example.com/mydirectory/myfile.aspx?id=1"); 
Uri directory = new Uri(baseAddress, "."); // "." == current dir, like MS-DOS 
Console.WriteLine(directory.OriginalString); 
+0

我有非常类似的东西,但我喜欢这么多,因为它有一个较少的函数调用! – 2009-10-23 23:44:32

+1

这一块石头! – 2011-11-04 09:13:50

+0

真不错的方法!如果基地址是一个目录,则需要使用“..”而不是“。”。此外,在这种情况下,请小心,因为如果尝试获取根目录的父级,则不会发生异常;你刚刚得到相同的Uri。 – 2012-12-14 00:31:06

12

这里是做的非常干净的方式。还有一个优点,就是可以使用任何网址:

var uri = new Uri("http://www.example.com/mydirectory/myfile.aspx?test=1"); 
var newUri = new Uri(uri, System.IO.Path.GetDirectoryName(uri.AbsolutePath)); 

注意:移除Dump()方法。 (这是一个从LINQPad这是我在那里验证此!)

+0

转储()做什么?此解决方案不在此编译。 – pyrocumulus 2009-10-23 23:35:00

+0

虽然没有转储()调用,但工作良好。 +1有一个很好的干净的解决方案,适用于每个网址(即使没有文件名)。 – pyrocumulus 2009-10-23 23:36:29

+0

没有更多的投票了:| – pyrocumulus 2009-10-23 23:38:13