我希望能夠從ASP.NET C#中的服務器端提取URL的子目錄的名稱並將其保存爲字符串。例如,可以說我有一個看起來像這樣的URL:從ASP.NET C#中的URL中提取子目錄名稱#
http://www.example.com/directory1/directory2/default.aspx
我怎麼會從URL中獲得的價值「directory2」?
我希望能夠從ASP.NET C#中的服務器端提取URL的子目錄的名稱並將其保存爲字符串。例如,可以說我有一個看起來像這樣的URL:從ASP.NET C#中的URL中提取子目錄名稱#
http://www.example.com/directory1/directory2/default.aspx
我怎麼會從URL中獲得的價值「directory2」?
可以使用string
類的split
方法將其分割上/
試試這個,如果你想選擇頁目錄
string words = "http://www.example.com/directory1/directory2/default.aspx";
string[] split = words.Split(new Char[] { '/'});
string myDir=split[split.Length-2]; // Result will be directory2
下面是例子來自MSDN。如何使用split
方法。
using System;
public class SplitTest
{
public static void Main()
{
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split)
{
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
// The example displays the following output to the console:
// This
// is
// a
// list
// of
// words
// with
// a
// bit
// of
// punctuation
// and
// a
// tab
// character
我會用.LastIndexOf( 「/」),並從向後工作。
您可以使用System.Uri來提取路徑的段。例如:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var uri = new System.Uri("http://www.example.com/directory1/directory2/default.aspx");
}
}
然後,屬性 「uri.Segments」 是含有這樣4支鏈段的字符串陣列(串[]):[ 「/」, 「directory1中/」, 「directory2 /」,「默認的.aspx「。
這是一個sorther代碼:
string url = (new Uri(Request.Url,".")).OriginalString
你可能想成爲一個更確切的一點:你想要的頁面之前的最後一個子目錄?即如果url是'http:// www.abc.com/foo/bar/baz/default.aspx',你想要'baz'? – Filburt
請看我更新的答案。 – jams