如何将URL拆分为字符串数组

时间:2014-06-11 19:36:16

标签: c# asp.net

我希望能够使用当前页面的网址并从最后一次提取/

例如,如果我的网址是:http://myintranet/guidelines/Home/Pages/mymed.aspx

我想提取mymed

到目前为止,我有这个:

string strEntity = HttpContext.Current.Request.Url.AbsolutePath;
Label2.Text = strEntity;

显示:

/guidelines/Home/Pages/mymed.aspx

我尝试使用Split("\\").Last();,但这对它不起作用,并说不能将字符串[]分配给字符串...

4 个答案:

答案 0 :(得分:8)

您可以使用System.IO.Path类中的GetFileNameWithoutExtension方法:

var uri = HttpContext.Current.Request.Url;
string fileName = Path.GetFileNameWithoutExtension(uri.AbsolutePath);

答案 1 :(得分:4)

Uri uri = new Uri("http://myintranet/guidelines/Home/Pages/mymed.aspx");
var segments = uri.Segments;
//do something with the array of segments

编辑:如上所述,您不需要创建一个Uri,因为您已有一个:

var lastPart = HttpContext.Current.Request.Url.Segments.Last();

答案 2 :(得分:3)

Uri uri = new Uri("http://myintranet/guidelines/Home/Pages/mymed.aspx");
var segments = uri.Segments;
var last = segments.Last(); //to get the last
var mymed = last.Split(".")[0]; //to separate the name from the extention

答案 3 :(得分:1)

您可以尝试这样的事情:

 var ub = new UriBuilder("http://myintranet/guidelines/Home/Pages/mymed.aspx");
 NameValueCollection nvc = HttpUtility.ParseQueryString(ub.Query);
 string page = nvc[nvc.Count - 1];
相关问题