Monday, 10 February 2014

Gem #2: Getting Silverlight Resources

Posting another little reminder... I had getting resource loading cracked for some images and graphics that I was using in one application with the following little set of code lines:

Image image = new Image();
string[] tmp = Assembly.GetExecutingAssembly().FullName.Split(',');
string path = "/" + tmp[0] + ";component/Graphics/";

image.Source = new BitmapImage(new Uri(path + imagefile, UriKind.Relative));

To access Assembly, System.Reflection; needs to be included.

The app had a set of images (png and jpg files) in a folder Graphics. What I had forgotten and struggled around with for 15mins was that the properties of the file need to have the Build Action set to Resource (see below).






This is all good. However recently I also wanted to use this to bring some XML information into the application. How to do that? After some fun, this seemed to work nicely:


string[] tmp = Assembly.GetExecutingAssembly().FullName.Split(',');
string path = "/" + tmp[0] + ";component/Data/";

Uri u = new Uri(path + "data.xml", UriKind.Relative);
Stream s = Application.GetResourceStream(u).Stream;

XDocument xdoc = XDocument.Load(s);

Remember you'll need to have using System.Xml.Linq; for this to work, which also needs to be added as a reference. In this case the XML files were in the folder Data.





No comments:

Post a Comment