我希望能够从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