2009-10-23 48 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