Click here to Skip to main content
Click here to Skip to main content

Using Resources in Your Application Part I - Simple Embedding.

, 8 Mar 2003
Rate this:
Please Sign up or sign in to vote.
The first article in a multi-part series, describing how to incorporate resources into your .NET application development.

Article1.jpg

Introduction

The .NET framework provides a rich feature set for working with resources in your application. Using resources in your application can help with packaging, deployment, maintenance, globalization and localization. Over the course of this multipart series, you will learn how to use resources and what they can do for you in your own applications.

What are resources?

Simply stated, resources are anything that your application uses to operate that is not considered executable code. Resource examples include icons, graphic files, strings, and objects. For each of these file types, the framework has provided methods to load these directly from their file. Given that, you may ask yourself "why do I need to use resources?". There are indeed a few very good reasons. First, you are able to group all your resources in one place. This keeps users from going to your applications directory and deleting files they have no business deleting. Second, it allows you to localize your application, provided, you do the work up front, to not use hard coded references to images and text in your application. Once you have the framework in place, you can distribute your application in a new language with relative ease.

Using the code

There are two applications included in this example. The first, the CreateResource is used to generate .resource files that can then be embedded into an application. The second is a simple example that demonstrates how to extract resources that have been embedded in your application assembly. These examples show how resources work in the .NET framework world. If you have Visual Studio, these features may come for free as part of that package.

Creating your resource file

Creating a resource file is relatively simple. The .NET framework provides all the functionality needed to take multiple resources and combine them into one resource file that can be included in your applications assembly. The ResourceWriter class implements the functionality described by the IResourceWriter interface, and is the primary class used when creating resources programmatically. To use the class you simply fire up the constructor, passing in the filename of what will be the resulting resource file.

IResourceWriter writer = new ResourceWriter(OutputFileName);

Resources can then be added to the resource file using the method IResourceWriter.AddResource (name, resource), where name is the string identifier that will be used to locate the resource and resource is either a Byte array, String, or object. Resources are written to the resource file in one of two ways. The first is after a call to IResourceWriter.Generate(). The second is after a call to IResourceWriter.Close() is made. Closing a resource file with pending additions will automatically call the Generate() method.

Armed with this knowledge you can easily construct an application to take the grunt work out of creating resource files. I have included one example with this article that I use on a regular basis to generate simple resource files that I can then embed into application assemblies. It reads in a text file containing the names of files to include as resources. It has the ability to process icons, bitmaps, strings, gifs, jpegs, and text files containing name-value pairs representing string resources.

CreateResource starts by initializing itself with an input file and output file. The input file is a simple text file containing files, one per line, which will be included as resources in the specified output resource file. If an output file is not specified, a default file name is chosen.

  ...
  if (args.Length == 0){
    Console.WriteLine("CreateResource <inputfile> <outputfile>");
    return;
  }
  
  if (!File.Exists(args[0])){
    Console.WriteLine(string.Format("File {0} does not exist", args[0]));
  }else{
    string OutputFileName = "";
    if (args.Length == 1){
      OutputFileName = "app.resources";
    }
    string InputFileName = args[0];
  ...

A new ResourceWriter is created returning an IResourceWriter interface. The input file is then opened with each line read in. An object is created based on the file type (with the exception of a text file) and added to the resource file using IResourceWriter.AddResource(). Text files passed in are opened and each name value pair specified is added to the resource file individually.

  ...
  IResourceWriter writer = new ResourceWriter(OutputFileName);
  StreamReader f = new StreamReader(InputFileName);
  string line = "";
  while (f.Peek() > -1){
    line = f.ReadLine(); 
    if (line.Length > 0){
      string ext = line.Substring(line.Length-3, 3);
      object res = null;
  
      string name = "";
      if (ext=="ico"){
        res = new Icon(line);
        name = line.Substring(0, - (ext.Length + 1)).ToUpper();
        writer.AddResource(name, res);
      }else if (ext=="bmp" | ext=="gif" | ext=="jpg"){
        res = Image.FromFile(line);
        name = line.Substring(0, line.Length - (ext.Length + 1)).ToUpper();
        writer.AddResource(name, res);
      }else if (ext=="txt"){
        //extract name value pairs
        StreamReader rf = new StreamReader(line);
        string resLine = "";
        while (rf.Peek() > -1){
          resLine = rf.ReadLine();
          if ( !resLine.StartsWith("[") && !resLine.StartsWith(";")){
            int i = resLine.IndexOf("=");
            name = resLine.Substring(0, i);
            i++;
            res =  resLine.Substring(i, resLine.Length - i);
            writer.AddResource(name, res);
          }
        }
      }
    }
  }
  writer.Close();

Once the input file has been processed, ResourceWriter.Close() is called to commit the changes to the resource file. It is that easy. You can use the compiled sample by typing CreateResource <inputfile> <outputfile> from the command line.

Embedding your resource file in your assembly

The resulting output file from running CreateResource is a single resource file containing the entire file specified in the input text file. In order to use this file in your application, you will need to embedded it as a resource in your assembly. Using the .NET framework C# compiler, it is done using the /resource:<filename> switch.

csc /out:main.exe /target:exe 
    /DEBUG+ /DEBUG:full /INCREMENTAL+ /resource:app.resources mainform.cs

Using your embedded resources in your application

Now that the resources have been embedded into the assembly, using them is a simple task. The second example application, ShowResources, shows how the ResourceManager class can be used to extract resources for use in an application.

The application opens the embedded resource by constructing a ResourceManager class. In this case, the parameters passed in are the base name of the resource (in our case app) file that was embedded and the currently running assembly. Notice we do not have to specify the .resource extension. The runtime takes care of that for us.

ResourceManager rm = new ResourceManager("app", this.GetType().Assembly);

To extract specific resources, the ResourceManager provides two methods, GetObject() and GetString(). You use GetObject() to extract anything from the resource file that is not a string. Using the methods are fairly simple. You specify the name specified when adding the resource and you get back the object.

      //a jpeg
      PictureBox jpg = new PictureBox();
      jpg.Dock = DockStyle.Top;
      jpg.Image = (Image)rm.GetObject("CODEPROJECT");
      ...
      //a bitmap
      PictureBox bm = new PictureBox();
      bm.Dock = DockStyle.Top;
      bm.Image = (Image)rm.GetObject("BACKGROUND");
      ...
      //strings
      listBox = new ListBox();
      listBox.Dock = DockStyle.Top;
      listBox.Height = 150;
      listBox.Items.Add(rm.GetString("rhyme1"));
      listBox.Items.Add(rm.GetString("rhyme3"));
      ...

In closing

You can see how easy it is to create and embed resources in your application. In part 2 we will explore more advanced uses of resources. If you have any questions about the included code or applications, please let me know.

Upcoming articles

  • Part 2 - Satellite Assemblies and Localization

History

  • 03/06/2003 - Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Dan Logan
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
QuestionHow use resourde with audio, video, database files in C# application? Pinmemberhitsmly19-Oct-04 22:41 
AnswerRe: How use resourde with audio, video, database files in C# application? PinmemberFlora PL14-Dec-04 2:43 
GeneralGood job PinmemberAntonio Barros4-Sep-04 8:26 
GeneralRe: Good job PinmemberDan Logan8-Sep-04 3:22 
QuestionHow create .res files? PinmemberLYASasha15-Apr-04 7:44 
GeneralUsing WAV resources PinmemberDave Hall15-Oct-03 20:31 
GeneralRe: Using WAV resources PinmemberPiledriver19757-Sep-05 10:37 
GeneralOT: Bobby Shaftoe PinmemberChristian Tratz13-Mar-03 6:54 
GeneralEmbedding files Pinmemberleppie10-Mar-03 9:55 
GeneralRe: Embedding files PinmemberDan Logan10-Mar-03 19:02 
GeneralRe: Embedding files PinmemberNemanja Trifunovic5-Sep-03 10:50 
GeneralRe: Embedding files Pinmemberleppie5-Sep-03 11:04 
GeneralRe: Embedding files PinmemberDan'M19-Nov-07 6:43 
GeneralNice PinmemberChopper10-Mar-03 3:01 
GeneralRe: Nice PinmemberDan Logan10-Mar-03 18:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411028.1 | Last Updated 9 Mar 2003
Article Copyright 2003 by Dan Logan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid