Search code examples
c#xmlurlimagesource

How to get image from relative URL in C#, the image cannot be in the project


I have a project where I'm loading relative image Uri's from an xml file. I'm loading the image like this:

if (child.Name == "photo" &&
    child.Attributes["href"] != null &&
    File.Exists(child.Attributes["href"].Value))
{
    Image image = new Image();
    image.Source = new BitmapImage(new Uri(child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
    images.Add(image);
}

Where the "child" object is an XmlNode which could looks like this

<photo name="info" href="Resources\Content\test.png"/>

During debug it seemd images is filled with actual images but when I want to see them in any way it shows nothing. Weird thing is when I include the images in my project it does work, I however dont want to do that since my point for using an xml file is so that it would be lost since you'd have to rebuild the program anyway after a change.


Solution

  • Not the perfect solution but its works nonetheless, I'm converting the relative Uri's to absolute ones like this

    if (child.Name == "photo" &&
        child.Attributes["href"] != null &&
        File.Exists(Environment.CurrentDirectory + child.Attributes["href"].Value))
    {
        Image image = new Image();
        image.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
        images.Add(image);
    }
    

    Only had to change all the Uri's in the xml to have a leading slash.