VirtualPathUtility Class

It's amazing how many different things are built-into the .NET framework.  As soon as you think you've seen just about everything you come across something that you didn't even realize was there.  That happened tonight as I read through a series of listserv posts covering different techniques for working with relative paths in ASP.NET applications. David Ebbo (Microsoft) mentioned using the VirtualPathUtility class (System.Web namespace) which I hadn't used or even heard of.  It greatly simplifies working with virtual directories....cool stuff.  Here's an example from the SDK:

protected void Page_Load(object sender, EventArgs e)
  {
    StringBuilder sb = new StringBuilder();
    String pathstring = Context.Request.FilePath.ToString();
    sb.Append("Current file path = " + pathstring + "<br>");
    sb.Append("File name = " + VirtualPathUtility.GetFileName(pathstring).ToString() + "<br>");
    sb.Append("File extension = " + VirtualPathUtility.GetExtension(pathstring).ToString() + "<br>");
    sb.Append("Directory = " + VirtualPathUtility.GetDirectory(pathstring).ToString() + "<br>");
    Response.Write(sb.ToString());
   
    StringBuilder sb2 = new StringBuilder();
    String pathstring1 = Context.Request.CurrentExecutionFilePath.ToString();
    sb2.Append("Current Executing File Path = " + pathstring1.ToString() + "<br>");
    sb2.Append("Is Absolute = " + VirtualPathUtility.IsAbsolute(pathstring1).ToString() + "<br>");
    sb2.Append("Is AppRelative = " + VirtualPathUtility.IsAppRelative(pathstring1).ToString() + "<br>");
    sb2.Append("Make AppRelative = " + VirtualPathUtility.ToAppRelative(pathstring1).ToString() + "<br>");
    Response.Write(sb2.ToString());
}





Follow me on Twitter @DanWahlin

Subscribe to my Free FlipBoard Magazines:


1 Comment (previous comments before moving to Disqus)

  • You have to be aware that this class is a crap, when it comes to the Combine method and it is best not to use it (this method) as some people point out on their blogs.