Buzz
Buzz

Reputation: 6320

Relative URI path is not working correctly

I am using these method to load images and resource directory dynamically, but they do not work in every case

new Uri(@"pack://application:,,/Images/lession_tab.png");

this method donot work for image but it work for Resource file.

new Uri("/project;component/Resources/Dictionary1.xaml", UriKind.Relative);

this method donot work for resouce directory but it works for image.

if i am getting this correctly pack://application work to get the local assesmbly path then why this not working for images
it is giving the exception Cannot locate resource 'images/lession_tab.png'.

Upvotes: 2

Views: 4529

Answers (2)

Ivan Leonenko
Ivan Leonenko

Reputation: 2383

Try to set Build Action = Resource and Copy to OutputDirectory = Do not copy for the first case.

Also you can use the following snippet to load "Resource" items:

public static class UriHelper
{
    /// <summary>
    /// Gets absulute URI for provided relative path
    /// </summary>
    /// <param name="baseType">Base type for ussage as URI root</param>
    /// <param name="relativePath">Relative path</param>
    /// <returns>Absolute Uri</returns>
    public static Uri GetUri(Type baseType, string relativePath)
    {
        Assembly oAssembly = Assembly.GetAssembly(baseType);
        AssemblyName oName = oAssembly.GetName();
        return new Uri( 
                String.Format(
                    "pack://application:,,,/{0};v{1};component/{2}",
                    oName.Name,
                    oName.Version.ToString(),
                    relativePath), 
                UriKind.Absolute);
    }
}

Upvotes: 1

quetzalcoatl
quetzalcoatl

Reputation: 33506

IIRC, images are by default added to the project "as Content" not "as Resource", and I'm not sure if you can refer to "content" with this URI syntax. What they have buildaction do they have? Resource or Content? If Content, I think you should just use plain URL like "/blah/image.png". Check http://msdn.microsoft.com/en-us/library/aa970069.aspx although they have there some strange wordings in a few places..

Another thing is that pack/application has three commas: like pack://application:,,,/ContentFile.xaml not two! Each ',' stands for an empty sub-locator, so make sure you tried with three, as the location meaning changes..

Upvotes: 2

Related Questions