web 2.0

News: Windows Phone 7 Phones Running Silverlight


How to Get Files From Resources in Silverlight 2.0

Questions like "How to load an embedded bitmap programmatically?" appear in Silverlight.net forum every single day, and some people actually think it is impossible to do such thing in Silverlight 2.0. Well, the truth is that not only is it possible but it is also damn easy.

Embed a File as Resource 

First thing first: create a new Silverlight Application Project, name it 'SilverlightApplication1'. Add a PNG image file to the project, rename it 'MyImage.png'. Click on the 'MyImage.png' in Solution Explorer to show its properties in Properties Window. 'Build Action' property should be 'Resource' to tell Silverlight compiler to embed 'MyImage.png' file as a resource. The 'Copy to Output Directory' property should be 'Do not Copy'.

 
Hit F5 to build the solution. 'MyImage.png' is now embedded in the application assembly (e.g. SilverlightApplication1.dll).

Load the Embedded File 

The quickest way to load an embedded file is by using the Application.GetResourceStream() method.

VB.NET

Imports System.Windows.Resources       ' StreamResourceInfo
Imports System.Windows.Media.Imaging   '
BitmapImage
... 

Dim sr As StreamResourceInfo = Application.GetResourceStream(_
    New Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative))
Dim bmp As New BitmapImage
bmp.SetSource(sr.Stream) 

C#

using System.Windows.Resources;      // StreamResourceInfo
using System.Windows.Media.Imaging;  // BitmapImage
....

StreamResourceInfo sr = Application.GetResourceStream(
    new Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);

Now you have the embedded bitmap in 'bmp'. Notice the the relative URI. There are literally three parts in the URI. 'SilverlightApplication1' is the name of assembly that has the embedded file. ';component/' is needed as separator, and finally the 'MyImage.png' is the relative path to the image. If the image were in 'Images' subfolder, the URI would be "SilverlightApplication1;component/Images/MyImage.png"

In case you don't know what to do with the bitmap, you can show it in an image element. 

img1.Source = bmp

This assumes that you had added the image element 'img1' to the Xaml file.

Include a File in Application Package Instead

Files can be included in the application .xap package instead of embedded in the application .dll assembly. Remember a .xap file is simply a zip file containing the compiled output files. You can rename the .xap extension to .zip, and then unzip the contents. To include a file in application package, simply set the 'Build Action' to 'Content' and rebuild the solution.

To load the file from the application package:

VB.NET 

Dim sr As StreamResourceInfo = Application.GetResourceStream(_
    New Uri("MyImage.png", UriKind.Relative))
Dim bmp As New BitmapImage
bmp.SetSource(sr.Stream)

C# 

StreamResourceInfo sr = Application.GetResourceStream(
    new Uri("MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);

Notice the URI is now just "MyImage.png". If the MyImage.png were stored in a subfolder 'Images', the URI would be "Images/MyImage.png". Remember, don't add the slash before the URI. The path "/Image/MyImage.png" would be wrong.

The Visual Studio Bug

If Application.GetResourceStream() returns nothing or null, it may be due to a bug in Visual Studio 2008 that prevents the compiler from rebuilding the resources. You can work around that by go to the project folder, find and delete all the *.resources files in the subfolders. You can also just delete the 'Obj' folder. Now hit F5 to build the solution.

Expect to repeat this workaround everytime you embeded additional files or make change to the 'Build Action' property. Because if you don't, Application.GetResourceStream() might return Nothing or Null. If left unhandled, a 'Null Reference' exception would be thrown.

Tags: ,

Silverlight 2.0 | Tutorial

Comments

Flavien , on 4/12/2008 12:59:03 AM Said:

Flavien

Hi, this is a good article, but when I try to set the source of the image:
img.Source = bmp;
nothing happens.

Neo , on 4/14/2008 4:30:37 PM Said:

Neo

Hi Flavien,

Did you set a break point to see if bmp or the resource stream contains the data?

It's also possible that the image element 'img' is outside the canvas or grid. Try setting the <Image Source="YourImage.png"> attribute in the Xaml, see if it works. Note that the Image element supports only JPEG and PNG images. Other file types especially BMP and GIF won't work.

Ricky , on 4/30/2008 5:46:52 PM Said:

Ricky

Hi there,

I got a resource file called UIResource.resx and it got some string in it.

How can I access the same?

Ricky

Cleyton , on 5/15/2008 4:00:45 AM Said:

Cleyton

Hi.

Can you help me? I am trying to load images from harddisk. But when I call System.IO.Directory.GetFiles(@"\imgs");
My silverlight app just fade away.

Neo , on 5/15/2008 2:35:01 PM Said:

Neo

@Ricky, Silverlight might not support .resx file yet. Last time I tried, it threw an exception.

@Cleyton, accessing user's file system is forbidden in Silverlight due to security concerns. So many classes in System.IO are restricted from uses. If you need to store files in user's file system, you can use IsolatedStorage class. If you need to download files off the web, use System.Net.WebClient class.

MarkT , on 5/29/2008 8:20:32 AM Said:

MarkT

What is the advantage to using GetResourceStream over just doing this:

  image.Source = new BitmapImage(new Uri("MyImage.jpg", UriKind.Relative));

MarkT , on 5/29/2008 5:14:48 PM Said:

MarkT

to follow up my own comment...

GetResourceStream works for both Resource and EmbeddedResource build actions on the image.

The shortcut I showed does not seem to work for EmbeddedResource.

fahimilyas.com , on 6/14/2008 6:39:20 PM Said:

pingback

Pingback from fahimilyas.com

Load Bitmap Image From Resource in a Single Line of Code | Silverlight

Martin , on 1/28/2009 10:46:18 PM Said:

Martin

When Including a File in Application Package:
- What if the application package is not the "main" xap file, but a separate xap file. Is it possible to somehow instruct SL to look in the other xap when resolving images?

pwdash4cash , on 3/8/2009 9:29:19 PM Said:

pwdash4cash

thanks for the direction dude!

cooldude055 , on 3/11/2009 9:08:15 PM Said:

cooldude055

Thanks for information, keep it up.

Gadgets in Future , on 3/23/2009 4:07:19 AM Said:

Gadgets in Future

this is a such a interesting blog...nice job

pandu , on 3/24/2009 12:15:13 AM Said:

pandu

I like the way you wrote the tips. It is quite easy to follow. Thanks, man...

cash4trends , on 4/1/2009 9:07:22 PM Said:

cash4trends

Thanks for sharing this one.

Leo , on 6/19/2009 11:27:05 AM Said:

Leo

Excellent blog post! Very helpful!

future gadgets , on 7/13/2009 10:21:03 PM Said:

future gadgets

this is some complex stuff... makes me wish i had taken some programming classes back in my college days...
-Jack

income protection , on 7/17/2009 7:04:34 PM Said:

income protection

A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that.

Virus removal , on 7/26/2009 8:50:30 PM Said:

Virus removal

Hey I just got through with the pages, I should say Pretty nice work done there.

video slot machine games , on 7/30/2009 8:51:17 PM Said:

video slot machine games

The problem with using the reader is that you require your tags to be in a specific order. However that's not how XML works.You could use the XML-to-LINQ, but that adds 50k to your XAP (why isn't it that these standard Dlls are part of the install gr

fap turbo , on 8/4/2009 7:17:44 PM Said:

fap turbo

Wow! What an in-depth study this is! I really appreciate the effort you have given to this post. I am looking forward for your next post! Thank you!

SEO , on 8/12/2009 8:10:05 PM Said:

SEO

How to use windows silverlight and there is no icon that shows that it is installed please help?

web marketing , on 8/18/2009 8:19:48 PM Said:

web marketing

What is 'Silverlight'? I have downloaded it from MSN, but don't know what are its usage and how it is used.?

Weight loss pills , on 8/23/2009 11:09:02 PM Said:

Weight loss pills

Thank you for sharing your knowledge. Please continue to post blogs like this to help people who are not so much of a techie, like me, to be motivated in using computers and internet. Great post!

Online Real Time Strategy Games , on 8/31/2009 6:54:05 AM Said:

Online Real Time Strategy Games



I like the way you wrote the tips. It is quite easy to follow. Thanks, man...

free diet plans , on 9/11/2009 6:12:56 AM Said:

free diet plans

the tips about silverlight has helped me a lot and thanks for sharing.

Emo , on 9/16/2009 7:23:23 PM Said:

Emo

When Including a File in Application Package:
- What if the application package is not the "main" xap file, but a separate xap file. Is it possible to somehow instruct SL to look in the other xap when resolving images?

Emo

Search engine marketing , on 9/23/2009 5:42:49 PM Said:

Search engine marketing

Hi,
   Extend the integration and productivity benefits of Visual Studio for developers to the entire software development team. Visual Studio and Microsoft Expression Studio share the same project and file formats, enabling developers and designers to collaborate freely while maintaining creative control.

Mobile based Embedded software’s , on 9/24/2009 8:41:17 PM Said:

Mobile based Embedded software’s

Good post, but have you thought about How to Get Files From Resources before?

UK van leasing , on 9/24/2009 9:00:58 PM Said:

UK van leasing

Thanks for sharing your views on the topic. It makes one think and look the other side of the story.  classifieds posting

j2me mobile application development , on 9/25/2009 12:07:31 AM Said:

j2me mobile application development

I was just thinking about Embed a File as Resource and you've really helped out. Thanks!

acai berry benefits , on 9/25/2009 10:34:57 PM Said:

acai berry benefits

Very good and informative article,thank you!

mobile application software development , on 10/2/2009 7:56:11 PM Said:

mobile application software development

That's great, I never thought about Embed a File as Resource like that before.

enterprise mobility solution , on 10/5/2009 1:18:01 AM Said:

enterprise mobility solution

Wow, I never knew that Embed a File as Resource. That's pretty interesting…

heartworm medicine , on 10/5/2009 7:02:21 PM Said:

heartworm medicine

Wow thanks, that can be a little tricky.

Cheap Travel Insurance , on 10/5/2009 10:03:55 PM Said:

Cheap Travel Insurance


Does service tax credit can be availed for the equipment hired?

cheap microwave , on 10/6/2009 5:00:53 AM Said:

cheap microwave

great info thanks!

remote shock collar , on 10/6/2009 8:43:13 AM Said:

remote shock collar

thanks for the heads up

best toaster , on 10/7/2009 3:10:32 AM Said:

best toaster

tis looks tricky, but will give a go when i finish work. thanks

Blocked soakaway , on 10/8/2009 6:49:12 AM Said:

Blocked soakaway

Happy I encountered this how to entry.  How to Get Files From Resources in Silverlight 20  - I have been looking for info on how to tackle this at the moment  and was pulled in by the title of your page in a search engine.  Studying books and papers has not been advantageous but a couple of web lookups has brought about a resolution which should help me a lot.  What would we do without the Net.  Thank you, I will use the info and must keep your site as a bookmark.

treatment medical news , on 10/10/2009 4:35:54 PM Said:

 treatment medical news


Thank you very much for this article, has served as much to me and my colleagues look forward to your website to gather more news

travel nursing , on 10/11/2009 1:46:53 AM Said:

travel nursing

the pros of using silverlight is that there is plenty of support for .Net languages; Great ease of use; Compute speeds beat competition but one disadvantage would be lack of out-of-the-box tools

SEO , on 10/12/2009 2:49:26 AM Said:

SEO

Topic which you have discussed is very useful and valuable.

cardell kitchen cabinets , on 10/12/2009 6:10:19 AM Said:

cardell kitchen cabinets

usegreat post thanks for sharing

Life Insurance , on 10/12/2009 7:22:38 PM Said:

Life Insurance

In runescape is it possible to have more than one silverlight?

Budget Car Insurance , on 10/15/2009 7:51:22 PM Said:

Budget Car Insurance

Hmm strange this post is totaly irrelevant to the search query I entered in google but it was listed on the first page.

Home loan , on 10/15/2009 8:58:05 PM Said:

Home loan

Excellently written article, if only all bloggers offered the same content as you, the internet would be a much better place. Please keep it up!

Annuities , on 10/17/2009 4:59:07 AM Said:

Annuities

Your post makes me clear that to load an embedded bitmap is an easy task. Before reading the post it wasn't. But now.... Thanks man. Carry on.

Atvservicemanuals , on 10/22/2009 6:45:00 AM Said:

Atvservicemanuals

Thanks for keeping updates..

--------------------------------------------------------------------------
<a href="www.scratchanddentappliances.net">scratch and dent</a> | <a href="http://www.craftsmansears.net">craftsman sears</a> | <a href="http://www.atvservicemanuals.net">atv service manuals</a>

jankeijzer.wordpress.com , on 11/19/2010 2:52:58 PM Said:

pingback

Pingback from jankeijzer.wordpress.com

Silverlight: Hoe refereer je een image, die in je XAP-file staat? « Jan Keijzer’s Weblog

koreyweldon.wordpress.com , on 4/8/2011 1:00:46 PM Said:

pingback

Pingback from koreyweldon.wordpress.com

Jailbreak iOS 4.3.1 on OS X or Windows with PwnageTool or Sn0wbreeze | koreyweldon

koreyweldon.wordpress.com , on 4/15/2011 1:20:39 AM Said:

pingback

Pingback from koreyweldon.wordpress.com

Photographers Survey Japan One Month After the Earthquake [Japan] | koreyweldon

unknownerror.net , on 6/19/2011 7:16:38 AM Said:

pingback

Pingback from unknownerror.net

[Silverlight入门系列]Silverlight读取web.config配置文件 | Unknown Error

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading