Tuesday, December 12, 2006

Reading embedded resources in C#

Reading embedded resources in .NET isn't particularly hard but since I always forget how to do it, I thought I'd write it down for my own benefit. 

First thing to do is set the Build Action property of the file you want to embed to 'Embedded Resource'. Next download my Resource Explorer from

http://www.doogal.co.uk/ResourceExplorer.php

After building the assembly, inspect it with this little utility to find out the name of the resource. If you're clever you can probably work out the resource name for yourself but I'm lazy and/or stupid (depends which day it is).

Finally, the code to read it is something like this.

Assembly assem = GetType().Assembly;   
using (Stream stream = assem.GetManifestResourceStream("resource name"))
{
  stream.Position = 0;
  // read data from stream

No comments: