How VirtualPathUtility combines paths in .Net 2.0 – level 100

This is a warning that the VirtualPathUtility class in .Net 2.0 takes
some time to understand the rules under which it operates.  It
wasn’t obvious to me, and I had to do some investigation to learn it’s
behavior.  I expected the following test to pass.  It didn’t.

        [Test]
        public void ShouldCombineTwoWebsitePaths()
        {
            string parentPath = “/websiteRoot”;
            string subDirectory = “newPage”;
            string expected = “/websiteRoot/newPage”;

           
string actual = VirtualPathUtility.Combine(parentPath, subDirectory);
            Assert.AreEqual(expected, actual);
        }

I expected it to actually “Combine” the base path and the path that was
relative to the base path.  After all, if these combine, the
product will be the sum of both, right?  Not really.  Here’s
my test output:

    String lengths differ.  Expected length=20, but was length=8.
    Strings differ at index 1.
   
    expected:<”/websiteRoot/newPage”>
     but was:<”/newPage”>
    ————^

Thanks to the first comment below, I realized that this method
tries to act like a web browser in resolving relative paths.  If I
add a “/” to the end of “/websiteRoot”, the test would have
passed.  As it stands, it assumes that “websiteRoot” is a page and not
a directory.

This entry was posted in ASP.NET, Coding Principles. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

3 Responses to How VirtualPathUtility combines paths in .Net 2.0 – level 100

  1. Justin M. Keyes says:

    @ ” Doh!”: the behavior of VirtualPathUtility.Combine() is counter to the behavior of System.IO.Path.Combine().

  2. Narwade says:

    plz will u help me in…………..

    i want to store images in separate virtual diectory & wann to access that at run time

  3. Doh! says:

    That’s how relative URLs get interpreted in HTML documents.
    It’s obvious to me and I haven’t even used the API. Combining isn’t appending a child name to a parent, it’s resolving a link relative to a page.

    If you want to resolve relative to a directory to get the path to a child in that directory, add a “/” to the directory name. Otherwise it’s going to be interpreted as a file, and so return a path to the child in the directory of that file.

Leave a Reply