Saturday, August 25, 2007

Using the tilde (~) in everywhere in your .aspx pages

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.

3 comments:

Anonymous said...

I write a comment each time I appreciate a article on a site or
if I have something to contribute to the conversation.

Usually it is triggered by the fire displayed in the article I looked at.
And after this article "Using the tilde (~) in everywhere in your .aspx pages".

I was actually excited enough to drop a thought :-P I
actually do have a couple of questions for you if it's allright. Is it simply me or does it look like a few of these comments look like they are left by brain dead individuals? :-P And, if you are posting at additional online social sites, I would like to follow everything new you have to post. Could you make a list all of all your community sites like your linkedin profile, Facebook page or twitter feed?

my web blog; Best online backup providers

Anonymous said...

I love looking through a post that can make men and women think.
Also, many thanks for permitting me to comment!

Here is my blog post; make beats

Anonymous said...

Hi friends, good piece of writing and nice urging commented at this
place, I am in fact enjoying by these.

Take a look at my website ... Green coffee bean weight loss