Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the (file) name of the current page in ASP.NET?

Tags:

c#

asp.net

How can I find the name of (default.aspx ) current page or web control in the code behind?

I want to write a superclass that uses this name.

like image 661
MHF Avatar asked Aug 29 '10 10:08

MHF


4 Answers

You mean that you want to find the original filename of the object that is currently executed? I.e., from inside a control MyControl you want to retrieve MyControlOnDisk.ascx? In general, this information is lost upon compiling, and moreover, many pages and controls are built on partial classes and the filenames they're from are compiled into a single assembly.

For a page, you can use the following, but only if the page is not internally redirected, is not instantiated as a class from another page, it is not a master page and you're not inside a static method:

string currentPageFileName = new FileInfo(this.Request.Url.LocalPath).Name;

In the case of a control, it is generally not possible as far as I know (it is compiled away), but perhaps someone can shed some light on this.

"i want to write a superclass that use this name "

I assume you mean to write a subclass? If you write a superclass you just create a virtual method and have it implemented in your subclass (the page). If you mean to create a subclass, you can take the classname of the page, which looks like this:

// current page
public partial class MyLovelyPage : System.Web.UI.UserControl

and use it like this to derive from it:

public partial class NewDerivedPage : MyLovelyPage
like image 121
Abel Avatar answered Oct 23 '22 17:10

Abel


I would recommend an alternative:

Server.MapPath(Page.AppRelativeVirtualPath)

This works with ASP.Net to get the full path and filename for the current page.

like image 25
Paco Zarate Avatar answered Oct 23 '22 17:10

Paco Zarate


Request.ServerVariables["SCRIPT_NAME"]
like image 45
ace Avatar answered Oct 23 '22 17:10

ace


if you not use Routing :

string sPath = HttpContext.Current.Request.Url.AbsolutePath;
        string[] strarry = sPath.Split('/');
        int lengh = strarry.Length;
        string sRet = strarry[lengh - 1]; 
like image 24
Akyegane Avatar answered Oct 23 '22 16:10

Akyegane