How to find (file name) the current page in ASP.NET?

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

I want to write a superclass that uses this name.

+4
source share
4 answers

Do you mean that you want to find the original name of the file that is currently running? Ie, from inside the MyControl control you want to get MyControlOnDisk.ascx ? In general, this information is lost during compilation, and, in addition, many pages and controls are built on partial classes, and the names of the files from which they are composed are compiled into one assembly.

For a page, you can use the following, but only if the page is not internally redirected, is not created as a class from another page, this is not the main page, and you are not in a static method:

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

In the case of the control, this is generally impossible, as far as I know (it is compiled), but maybe someone can shed some light on this.

"I want to write a superclass that uses this name"

I assume you want to write a subclass? If you write a superclass, you simply create a virtual method and implement it in your subclass (page). If you want to create a subclass, you can take the class name of the page, which looks like this:

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

and use it in such a way as to extract from it:

 public partial class NewDerivedPage : MyLovelyPage 
+10
source

I would recommend an alternative:

 Server.MapPath(Page.AppRelativeVirtualPath) 

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

+3
source

if you are not using Routing:

 string sPath = HttpContext.Current.Request.Url.AbsolutePath; string[] strarry = sPath.Split('/'); int lengh = strarry.Length; string sRet = strarry[lengh - 1]; 
+1
source
 Request.ServerVariables["SCRIPT_NAME"] 
0
source

All Articles