tags:

views:

47

answers:

2

Hi,

I am using C#. Below is my sample code.

private void Page_Load(object sender, System.EventArgs e)
{
    string str = Request.UrlReferrer.ToString();   
    Label1.Text = str;  
}

The result in Label1.Text is http://localhost:82/data/WebForm1.aspx.

Now I want the result "WebForm1.aspx" in Label1.Text

can you please help me?

Thanks.

A: 

Try the LocalPath property on the UrlReferrer:

Label1.Text = Request.UrlReferrer.LocalPath;

It should provide you with just the filename.

Edit: this seems to also include the path, so only works for root.

In which case, you're better off just using Substring():

string str = Request.UrlReferrer.ToString();
Label1.Text = str.Substring(str.LastIndexOf('/')+1);
Wim Hollebrandse
Thanks! it is giving me /data/WebForm1.aspx, however i want only WebForm1.aspx. Please suggest
MKS
Thanks! what in that case if my url returns http://localhost:82/data/WebForm1.aspx?test="hello". I mean if there is querystring in url did the above logic for substring will work
MKS
It will include the querystring, so then just perform the `Substring()` operation on the `LocalPath` property. I don't think LocalPath contains the querystring.
Wim Hollebrandse
+4  A: 

If you want only the part after the last / in the URL, calling the System.IO.Path.GetFileName() method on the Uri.LocalPath should do the trick:

System.IO.Path.GetFileName(Request.UrlReferrer.LocalPath);

If you want the output to keep query string information from the URI, use the PathAndQuery property:

System.IO.Path.GetFileName(Request.UrlReferrer.PathAndQuery);
Jørn Schou-Rode
Thanks this also worked, just to confirm that if my url contains some querystring then also my result will be WebForm1.aspx or not
MKS
LocalPath will strip that off.
Wim Hollebrandse
Great Thanks Dear for your help!
MKS
Answer expanded to include a version that retains the query string.
Jørn Schou-Rode