Click here to Skip to main content
15,860,859 members
Articles / Programming Languages / C#
Article

Using Resources in Your Application Part I - Simple Embedding.

Rate me:
Please Sign up or sign in to vote.
4.79/5 (19 votes)
8 Mar 20035 min read 105K   2.3K   88   15
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.

C#
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.

C#
...
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.

C#
...
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.

C#
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.

C#
//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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow use resourde with audio, video, database files in C# application? Pin
hitsmly19-Oct-04 21:41
hitsmly19-Oct-04 21:41 
AnswerRe: How use resourde with audio, video, database files in C# application? Pin
Flora PL14-Dec-04 1:43
Flora PL14-Dec-04 1:43 
GeneralGood job Pin
Antonio Barros4-Sep-04 7:26
professionalAntonio Barros4-Sep-04 7:26 
GeneralRe: Good job Pin
Dan Logan8-Sep-04 2:22
Dan Logan8-Sep-04 2:22 
QuestionHow create .res files? Pin
LYASasha15-Apr-04 6:44
LYASasha15-Apr-04 6:44 
GeneralUsing WAV resources Pin
Dave Hall15-Oct-03 19:31
Dave Hall15-Oct-03 19:31 
GeneralRe: Using WAV resources Pin
Piledriver19757-Sep-05 9:37
Piledriver19757-Sep-05 9:37 
GeneralOT: Bobby Shaftoe Pin
Christian Tratz13-Mar-03 5:54
Christian Tratz13-Mar-03 5:54 
GeneralEmbedding files Pin
leppie10-Mar-03 8:55
leppie10-Mar-03 8:55 
GeneralRe: Embedding files Pin
Dan Logan10-Mar-03 18:02
Dan Logan10-Mar-03 18:02 
GeneralRe: Embedding files Pin
Nemanja Trifunovic5-Sep-03 9:50
Nemanja Trifunovic5-Sep-03 9:50 
GeneralRe: Embedding files Pin
leppie5-Sep-03 10:04
leppie5-Sep-03 10:04 
GeneralRe: Embedding files Pin
Dan Suthar19-Nov-07 5:43
professionalDan Suthar19-Nov-07 5:43 
GeneralNice Pin
Chopper10-Mar-03 2:01
Chopper10-Mar-03 2:01 
GeneralRe: Nice Pin
Dan Logan10-Mar-03 17:48
Dan Logan10-Mar-03 17:48 

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

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