ASP.NET: Get Page's filename
I have an ASPX page named Default.aspx
. From its codebehind on Page_Load()
, I would like to get "Default.aspx", alone, into a string:
protected void Page_Load(object sender, EventArgs e)
{
string aspxFileName = ?;
}
What should I repl开发者_JS百科ace ?
with—what will get me the ASPX filename?
System.IO.Path.GetFileName(Request.PhysicalPath);
protected void Page_Load(object sender, EventArgs e)
{
string cssFileName = Path.GetFileName(this.Request.PhysicalPath).Replace(".aspx", ".css");
}
Some short answers are already taken so, for fun, and because you'll likely want to do this from other Web Forms, here's an expanded solution that will affect all Web Forms in your project uniformly (includes code to get a filename as requested).
Make an extension method for the System.Web.UI.Page class by putting this code in a file. You need to use .NET 3.5.
namespace MyExtensions {
using System.Web.UI;
static public class Extensions {
/* You can stuff anybody else's logic into this
* method to get the page filename, whichever implementation you prefer.
*/
static public string GetFilename(this Page p) {
// Extract filename.
return p.AppRelativeVirtualPath.Substring(
p.AppRelativeVirtualPath.IndexOf("/") + 1
);
}
}
}
To get the filename from any ASP.NET Web Form (for example in the load method you specified):
using MyExtensions;
protected void Page_Load(object sender, EventArgs e) {
string aspxFileName = this.GetFilename();
}
Call this method on any Web Form in your project.
精彩评论