post icon

Silverlight Tip of the Day #12 – Getting an Images Source File Name

Once you have an image loaded how do you go back and get the original file name for the source file?

This can be accomplished through the Uri property of the images Source. However, you must first typecast the images Source to be a BitmapImage. The Uri has a property called OriginalString that returns the full relative path to the image file.

Example:

public string GetImageSourceFile(Image img) 
{ 
     BitmapImage bi = (BitmapImage)img.Source; 
     Uri uri = bi.UriSource; 
     return uri.OriginalString; 
}

BitmapImage can be found in the System.Windows.Media.Imaging namespace.

Thank you,

–Mike

 
04. May, 2010

4 Comments

Leave a comment
  1. Vikas
    04. May, 2010 at 2:21 pm #

    Thanks Mike
    working XAML us feel that Source is a string but ,Image.Source is of type BitmapImage and not string .
    msdn states :
    You can set this property in XAML, but in this case you are setting the property as a URI. The XAML behavior relies on underlying type conversion that processes the string as a URI, and calls the BitmapImage(Uri) constructor. This in turn potentially requests a stream from that URI and returns the image source object.

    Thanks
    Vikas Amin
    Credit Suisse

  2. Snowman
    04. May, 2010 at 2:32 pm #

    Sorry, I am not sure what you are saying. Source is a BitmapImage yes but from that you can get the string url path that specifies where the image came from. No?

  3. Martin
    01. Oct, 2010 at 2:39 am #

    One can put it in one line of code:

    // C#
    SourceInfo.Text = ((BitmapImage)(SampleImage.GetValue(Image.SourceProperty))).UriSource.OriginalString;

    ‘ VB
    SourceInfo.Text = CType(SampleImage.GetValue(Image.SourceProperty), BitmapImage).UriSource.OriginalString

Trackbacks/Pingbacks

  1. Dew Drop – May 5, 2010 | Alvin Ashcraft's Morning Dew - 05. May, 2010

    [...] Silverlight Tip of the Day #12 – Getting an Images Source File Name (Mike Snow) [...]