Wednesday, September 28, 2005

Embedding and using text resource files in C# (also a little about normally embedded resources)

Sometimes, you might want to embed an entire text file (or any other format for that matter) into your .Net assembly. (As opposed to creating a resource file that might contain culture specific resources for access at runtime) To do this you add the file to your project. You then have to set the file to be an embedded resource. (this is done on the property page of the file). Once that is done you can use the GetManifestResourceStream method of the System.Assembly class to retrieve the data. You can do this using the following code snippet: Assembly currentAssembly = Assembly.GetExecutingAssembly(); using( Stream stream = currentAssembly.GetManifestResourceStream("projectName.Folder.resourceName.extension") ) { try { using( StreamReader reader = new StreamReader(stream) ) { string text = reader.ReadToEnd(); using (StreamWriter sw = new StreamWriter(filePath,false,System.Text.Encoding.ASCII)) { sw.WriteLine(text); } } } catch(Exception e) { MessageBox.Show(e.Message); } One of the important things to remember is that when retrieving the resource you need to fully qualify its name. Normally this will be ProjectName.Folder.ResourceName.Extension. This name is case sensitive (omit the folder if the resource file is in the root folder of the project). If instead, you want to create the resource file to contain multiple items within it (normally used to store grouped items, like strings for a specific culture), then you would use the ResourceManager. To do this you create a resource file: IResourceWriter rw = new ResourceWriter(ResourceFileName); and then call AddResource to attach each item. rw.AddResource(resourceItemName,resourceItem); To read the resource file you can open it directly or embed it in the assembly and open it from there. To read the resource file directly: IResourceReader rr = new ResourceReader(resourceFileName); and then use the enumerator to read the key value pairs of resource items. To read the resource from the assembly. First embed the resource into the assembly, by adding the file to the project and setting its property to Embedded resource. then use the following snippet: ResourceManager rm = new ResourceManager(resourceFileName,Assembly.GetExecutingAssembly()); string text = rm.GetString(resourceItemName); object val = rm.GetObject(resourceItemName);

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.