Silverlight: Accessing files outside of the ClientBin directory of your website using a relative URI

Accessing an arbitrary file on your website is a very common need in RIA scenarios. This is easily done from Silverlight when the files you are trying to access are under the ClientBin directory, or given an absolute URI path to the targeted file. Unfortunately, the ../ notation in Silverlight URIs  does not go up from the ClientBin directory.

Let’s say you want to access MyRobots.jpg from your site’s Images directory :

image

As previously stated, using ../ or just / in Silverlight 3 will only go up to the ClientBin directory. The only way to gain access to the image is to use an absolute URI in the form of https://www.abc.com/mysite/Images/MyRobots.jpg, which you probably do not want as moving your application to another site would require a recompilation of your program.

The solution is to determine at runtime the absolute path of your application, and use it as a prefix to the resources you want to access. You can get your application’s absolute URI using the following code:

Application.Current.Host.Source.AbsoluteUri

Just remove the ClientBin part and you are ready to go:

Regex.Replace(Application.Current.Host.Source.AbsoluteUri, @"ClientBin/[\w/.]*", string.Empty);

As usual, an example project is attached, where I make use of this technique in a Binding with a Converter and a static property.

<Image Source="{Binding Converter={StaticResource WebSiteRelativeURIConverter},ConverterParameter=Images/,Path=MyImageFilename/>

image

Have fun!

RelativeExternalUris_en.zip

Comments

  • Anonymous
    December 21, 2011
    The comment has been removed
  • Anonymous
    July 05, 2012
    if url https then its not work