开发者

get absolute file path from image in WPF

I have something like this开发者_如何学C in my xaml:

<Grid>
    <Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>

How can I get (using my code-behind C# code) the absolute path of the image source?


The method which works for me every time is this simple line

(YourImage.Source as BitmapImage).UriSource

In addition you can work on AbsolutePath or AbsoluteUri of UriSource returned according to your need.


When converted from a Uri string or filename, the ImageConverter creates a BitmapDecoder and extracts its first Frame. Getting the Uri should be possible with:

((BitmapFrame)image.Source).Decoder.ToString()

Note that this will generally return an absolute Uri rather than the original Uri found in the XAML. If you need the exact original Uri from the XAML, it is found in the _uri field of the BitmapDecoder but you'll need reflection and elevated code permissions to get to it, plus your code may not work in future NET Framework versions.


You could try this:

string path = ((BitmapImage)image.Source).UriSource.AbsolutePath;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜