amateur
amateur

Reputation: 44663

get current page from url

I want to write a c# method to retrieve the current page. eg Default6.aspx I know I can do the following:

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

but how can I get Default6.aspx? And if the url is http://localhost:1302/TESTERS/, my method should return default.aspx

Upvotes: 38

Views: 111390

Answers (6)

cl0rkster
cl0rkster

Reputation: 369

Request.Url.Segments.Last()

Another option.

Upvotes: 1

acermate433s
acermate433s

Reputation: 2554

The class you need is System.Uri

Dim url As System.Uri = Request.UrlReferrer 
Debug.WriteLine(url.AbsoluteUri)   ' => http://www.mysite.com/default.aspx
Debug.WriteLine(url.AbsolutePath)  ' => /default.aspx
Debug.WriteLine(url.Host)          ' => http:/www.mysite.com
Debug.WriteLine(url.Port)          ' => 80
Debug.WriteLine(url.IsLoopback)    ' => False

http://www.devx.com/vb2themax/Tip/18709

Upvotes: 13

Paul Alexander
Paul Alexander

Reputation: 32377

Path.GetFileName( Request.Url.AbsolutePath )

Upvotes: 50

scartag
scartag

Reputation: 17680

You could try this below.

string url = "http://localhost:1302/TESTERS/Default6.aspx";

string fileName = System.IO.Path.GetFileName(url);

Hope this helps.

Upvotes: 1

nrph
nrph

Reputation: 335

Try this:

path.Substring(path.LastIndexOf("/");

Upvotes: 6

Neil Knight
Neil Knight

Reputation: 48587

A simple function like below will help :

public string GetCurrentPageName() 
{ 
    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); 
    string sRet = oInfo.Name; 
    return sRet; 
} 

Upvotes: 5

Related Questions