Get the current file being processed in ASP.net
I have a requirement where I want to trace what file is being processed by .net runtime. I mean if it is processing usercontrol x.ascx then it should return the whole path of that, and if it is processing usercontrol y.ascx it should retur开发者_开发知识库n that.
There are some candidates properties.
Request.AppRelativeCurrentExecutionFilePath
or
TemplateControl.AppRelativeVirtualPath.
Can somebody help me with this, or is there any other property that can give me the path.
Request.AppRelativeCurrentExecutionFilePath
should do what you need. Is it producing unexpected results?
Update
You should be able to retrieve any UserControl(s) currently being executed by enumerating the Controls collection of the current page handler. Assuming an external context, here's an example that should work:
public static string[] GetCurrentUserControlPaths() {
if(HttpContext.Current == null) return new string[0];
if(!(HttpContext.Current.Handler is Page)) return new string[0];
var page = (HttpContext.Current.Handler as Page);
var paths = ControlAggregator(page, c => c is UserControl).Cast<UserControl>().Select(uc => uc.AppRelativeVirtualPath);
if(page.Master != null) {
paths.Concat(ControlAggregator(page.Master, c => c is UserControl).Cast<UserControl>().Select(uc => uc.AppRelativeVirtualPath));
}
return paths.ToArray();
}
public static Control[] ControlAggregator(this Control control, Func<Control, bool> selector) {
var list = new List<Control>();
if (selector(control)) {
list.Add(control);
}
foreach(Control child in control.Controls) {
list.AddRange(ControlAggregator(child, selector));
}
return list.ToArray();
}
精彩评论