If you are not familiar with tilde usage in ASP.NET, then you are sooooo missing out. Many times our development environment is totally different than a production server. We may test our application using a virtual directory on our development machine, but may publish to a dedicated root site.
So when you add an image or a link, you must always be aware of the type of path you provide - relative, absolute, etc. Well, one of the best little tricks of ASP.NET is the tilde (~). This is essentially a shortcut for the HttpRuntime.AppDomainAppVirtualPath property, which refers to the virtual application root, not the root of the web server.
protected override void Render(HtmlTextWriter writer)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
htw.Flush();
ms.Position = 0;
TextReader tr = new StreamReader(ms);
string output = tr.ReadToEnd();
string newOutput = ReplaceWithAppPath(output);
writer.Write(newOutput);
htw.Close();
sw.Close();
ms.Close();
}
public static string ReplaceWithAppPath(string str)
{
string appPath = HttpContext.Current.Request.ApplicationPath;
//Ensure the app path ends w/ a slash
if (!appPath.EndsWith("/"))
appPath += "/";
return str.Replace("~/", appPath);
}
You can put that code in MasterPage, Page, or control.
Saturday, August 25, 2007
Subscribe to:
Comments (Atom)