Jeffrey Palermo (.com)

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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.


Posted Fri, Mar 10 2006 10:44 PM by Jeffrey Palermo

[Advertisement]

Comments

Doh! wrote That's exactly what it's meant to do
on Sat, Mar 11 2006 9:50 AM
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.
Narwade wrote re: How VirtualPathUtility combines paths in .Net 2.0 - level 100
on Tue, Jul 17 2007 7:08 AM

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

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

Justin M. Keyes wrote re: How VirtualPathUtility combines paths in .Net 2.0 - level 100
on Thu, Sep 6 2007 8:27 PM

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