How to grab .aspx Page Name from the URL?

What object can I use to get the current PageName.aspx (including the extension .aspx) from the URL? I can’t find what object and method to allow me to grab this when I’m on a page.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Note that sometimes, on shared hosting like GoDaddy, you might not have the permission to create a new FileInfo object. Yes, believe it.

So I suggest you use this snippet:

string fullPath = /* System.Web.HttpContext.Current. (optional in most cases) */ Request.Url.AbsolutePath;
string fileName = System.IO.Path.GetFileName(fullPath);

Enjoy 🙂

Method 2

Pino here’s the source lil man: http://www.devx.com/tips/Tip/42433

  string sPagePath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
    System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sPagePath);
    string sPageName = oFileInfo.Name;

Method 3

http://www.aspcode.net/Get-current-page-name.aspx

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; 
}

Method 4

Request.Url.AbsolutePath

Split about ‘/’, last item is your file name.

Method 5

Path.GetFileName(Request.PhysicalPath) can be used to fetch the actual file name

Method 6

I used: Request.Url.LocalPath, which gave me “/default.aspx”, even when full URL would be https://www.example.com/?foo=bar. You just need to strip the leading /.

Method 7

How about this:

    var pageName = System.IO.Path.GetFileName(Request.Url.ToString());
    Response.Write(pageName);

Method 8

string pageName = Path.GetFileName(Request.Path);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x