I want to be able to extract the name of a sub-directory of a URL and save it to a string from the server-side in ASP.NET C#. For example, lets say I have a URL that looks like this:
http://www.example.com/directory1/directory2/default.aspx
How would I get the value 'directory2' from the URL?
Uri class has a property called segments :
var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");
Request.Url.Segments[2]; //Index of directory2
这是一个分类代码:
string url = (new Uri(Request.Url,".")).OriginalString
我使用.LastIndexOf(“/”)并从那里开始向后工作。
You can use System.Uri to extract the segments of the path. For example:
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");
}
}
Then the property "uri.Segments" is a string array (string[]) containing 4 segments like this: ["/", "directory1/", "directory2/", "default.aspx"].
You can use split
method of string
class to split it on /
Try this if you want to pick page directory
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
Here is example from MSDN. How to use split
method.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.