Friday 11 July 2014

Using Resources within your Winform application

Typically, there are two types of resources available to any piece of software - those held within the code and those outside of the code. Both have their advantages and both their disadvantages.

If a resource (say an image) is compiled into the final assembly, the final assembly can be huge, but the nice thing is that everything is inside the assembly, so no danger pictures or sounds going missing causing the final application not work

If a resource is outside of the application, the benefit is a smaller assembly size, but everything needs to be loaded in which slows things down and has an added draw back of the application failing if a resource is missing.

A big advantage though of the resource being outside of the compiled binary is that if the development or proof of concept is done in VB.NET, the final version can be written in C# and use the same resources used.

Resources are handled using the System.Resources class. The following example loads a file which is a resource. In this case, it loads a picture

var executingAssembly = Assembly.GetExecutingAssembly();
try
{
   var resourceStream =
      executingAssembly.GetManifestResourceStream(xml.picname);
   pictureBox1.Image = new Bitmap(resourceStream);
}
catch (System.ArgumentException)
{
   MessageBox.Show("Unable to find element picture",
                   "Picture not found", MessageBoxButtons.OK);
}


xml.picname is read in from another method and just contains the name of an image held in the resources directory.

No comments:

Post a Comment