Home
Manage Your Code
Snippet: Read a file from an embedded resource. (C#)
Title: Read a file from an embedded resource. Language: C#
Description: reads a file from a resource. This assumes you have added a file called "image.jpg" to your project and set it's attribute to "Embedded Resource". This method can be used to read the file into a byte array. Views: 1521
Author: Justin Jones Date Added: 5/24/2007
Copy Code  
1List<string> resourcenames = new List<string>();
2resourcenames.AddRange(Assembly.GetExecutingAssembly().GetManifestResourceNames());
3string resourcename = resourcenames.Find(delegate(string item) { return item.EndsWith("image.jpg"); });
4Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcename);
5BinaryReader br = new BinaryReader(s);
6_image = br.ReadBytes((int) s.Length);
7br.Close();
8s.Close();
Usage
as is, or can be encapsulated in a method.  

I havent tried it, but I think you could read a text file (e.g. xml) using the StringReader class instead of BinaryReader.
Notes
This code has followed me around for a while and is a bit dated, and probably still works on .net 1.1 (once you replace the generic list code). I think there are better, more efficient ways to do this now in 2.0+. Look at the ResourceManager class.