How to embed and use C # to access resources in a detailed code

Source: Internet
Author: User
How do I use embedded resources in C #?

This step-through article describes how to use C # to embed a resource as part of an assembly, and then access the resource at run time.

Overview

The. NET Framework can encapsulate files as part of a compiled assembly. These files are called embedded resources. These resources are fully independent of the assemblies associated with the. Resources and. resx files. You can access these resources at run time through the assembly class of the System.Reflection namespace.

The main advantage of an embedded manifest resource is that because these files are part of the compiled assembly, users cannot accidentally delete or mistakenly drop them into your application, which in some cases may block the execution of a program's vital files. One limitation of this approach is that you cannot save any changes to this file's assembly without recompiling the program. Because of this, only files that are not changed during the lifetime of the application that are embedded as resources are included.

Step into the show

To add embedded resources to your project, you must first add the files for a part of your project. After you add a file to the project, you can access and display resources through the System.Reflection namespace.

Add an embedded Resource

To add text files and image files to your project as a resource, follow these steps:

    1. Create a new Windows application project for this demo. This form is used to display resources that are accessed at run time from the executing assembly.

    2. Right-click the project name, click Add , and then click Add New Item

    3. In new project dialog box, from the menu, select text file , and name the file MyTextFile.txt. You open the file in the Integrated development environment (IDE), add some text, and then close the file.

    4. Repeat steps 1 and 2 to add the bitmap image to the project, but instead of selecting text file as the new project type, select bitmap File , and then change the file name to myimage.bmp . When you open a new image in the IDE, the content is drawn on the image, and then the file is closed.

    5. Right-click the file text or bitmap and select Properties

    6. In the Properties dialog box, locate the build action The/strong> property. By default, this property is set to content . Click the property and change the Build Action property to Embedded Resource

    7. Repeat steps 4 and 5 for another file.

The next time you build your project, the compiler adds these files to your assembly. When it is contained in a project, the compiler adds the project's root namespace to the name of the resource. For example, if your project's root namespace is mynamespace, the resources are named MyNamespace.MyTextFile.txt and MyNamespace.MyImage.bmp.

Note : The name of the resource file is case sensitive. When you access a resource, you must use the exact spelling and capitalization of the file name. If you do not use the exact spelling and capitalization of the file name, the method is called to access Manifestresourcestream to perform any action , and the system does not throw an exception.

Note : If you want to verify these resource names, you can use the Microsoft intermediate language Disassembler (ILDASM) to view inventory data, which lists the resources that are included.

Access resources

To access resources that have been embedded in your assembly's manifest, in the System.IO and System.Reflection namespaces, as described below:

   Using System.IO;   Using System.Reflection;

The System.IO namespace provides a way to define the flow and the classes provided by the assemblies defined in the system.reflection namespace to access the embedded resources in the assembly.

When declaring in the following General declaration area, the resources from the Assembly are read when the form is loaded:

   Assembly _assembly;   Stream _imagestream;   StreamReader _textstreamreader;

note to access the Load event for a form in the Code Editor, double-click the form in the design editor.

To read the resources from the Assembly that is executing the current code, you must obtain an instance of the assembly. To do this, use the assembly,getexecutingassembly method, as follows:

   _assembly = assembly.getexecutingassembly ();

Reads information from the resource into the stream and executes on the GetManifestResourceStream method call. The parameter passed to this method is the name of the resource to be accessed. You execute the form's Load event, and then read two resources to its corresponding stream.

   _imagestream = _assembly. GetManifestResourceStream ("MyNameSpace.MyImage.bmp");   _textstreamreader = new StreamReader (_assembly. GetManifestResourceStream ("MyNameSpace.MyTextFile.txt"));

The code in the form's Load event is as follows:

   Try   {      _assembly = assembly.getexecutingassembly ();      _imagestream = _assembly. GetManifestResourceStream ("MyNamespace.MyImage.bmp");      _textstreamreader = new StreamReader (_assembly. GetManifestResourceStream ("MyNamespace.MyTextFile.txt"));   }   Catch   {      MessageBox.Show ("Error accessing resources!");   }

In the try-catch statement, called in. NET, structured error handling can be used to catch any errors that may occur when an instance of an assembly class accesses a resource.

Show Resources

This example uses two buttons to display the embedded resource. When you click the first button, the bitmap image based on reading the resource from the assembly is created and displayed in the picture box control of the form. The second button of the text resource reads from and displays the text in the text box.

To display the embedded resources, follow these steps:

  1. Add a picture box control to the form.

  2. Add a new button control to the form, and then change its Text property to display the image

  3. Double-click the button to open its click event in the Code Viewer, and then paste the following code in this case:

  4.    Try   {      picturebox1.image = new Bitmap (_imagestream);       }   Catch    {      MessageBox.Show ("Error creating image!");   }

    The code generates a new instance of the bitmap that reads the resource stream in the form-based Load event.

  5. Add a text box control to the form.

  6. Add another button control to the form, and then change its text property to get text

  7. Double-click the button that opens the click_event button in the design editor, and then paste the following code in the event:

  8.    Try   {      if (_textstreamreader.peek ()! =-1)      {         TextBox1.Text = _textstreamreader.readline ()      }   }   Catch   {      MessageBox.Show ("Error writing text!");   }

    This code determines whether the characters to be read still exist in the stream. If the character is found, the line is read in the text box.

  9. Press the F5 key to run the application.

The complete code

   Using System;   Using System.Drawing;   Using System.Collections;   Using System.ComponentModel;   Using System.Windows.Forms;   Using System.Data;   Using System.IO;   Using System.Reflection;      namespace MyNamespace {//<summary>//Summary description for FORM1. </summary> public class Form1:System.Windows.Forms.Form {private SYSTEM.WINDOWS.FORMS.PICTU         Rebox PictureBox1;         Private System.Windows.Forms.TextBox TextBox1;         Private System.Windows.Forms.Button button1;         Private System.Windows.Forms.Button button2;         <summary>//Required designer variable.         </summary> private System.ComponentModel.Container components = null;            Public Form1 () {////Required for Windows Form Designer support.            InitializeComponent (); Todo:add any constructor code after InitializecomponenT call.         }//<summary>//clean up any resources being used.            </summary> protected override void Dispose (bool disposing) {if (disposing) {if (Components! = NULL) {components.               Dispose (); }} base.         Dispose (disposing); } #region Windows Form Designer generated code///<summary>//Required method for Designer s         Upport-do not modify//the contents of this method with the Code editor. </summary> private void InitializeComponent () {this.picturebox1 = new system.windows .            Forms.picturebox ();            This.textbox1 = new System.Windows.Forms.TextBox ();            This.button1 = new System.Windows.Forms.Button ();            This.button2 = new System.Windows.Forms.Button (); This.           SuspendLayout (); PictureBox1//this.pictureBox1.Location = new System.Drawing.Point (4, 8);            This.pictureBox1.Name = "PictureBox1";            This.pictureBox1.Size = new System.Drawing.Size (284, 192);            This.pictureBox1.TabIndex = 0;            This.pictureBox1.TabStop = false;            TextBox1//this.textBox1.Location = new System.Drawing.Point (92, 236);            This.textBox1.Name = "TextBox1";            This.textBox1.Size = new System.Drawing.Size (192, 20);            This.textBox1.TabIndex = 1;            This.textBox1.Text = "TextBox1";            Button1//this.button1.Location = new System.Drawing.Point (8, 208);            This.button1.Name = "Button1";            This.button1.TabIndex = 2;            This.button1.Text = "Show Image";            This.button1.Click + = new System.EventHandler (This.button1_click); button2//this.button2.Location = new System.Drawing.Point (8, 236);            This.button2.Name = "Button2";            This.button2.TabIndex = 3;            This.button2.Text = "Get Text";            This.button2.Click + = new System.EventHandler (This.button2_click); Form1//this.            AutoScaleBaseSize = new System.Drawing.Size (5, 13); This.            ClientSize = new System.Drawing.Size (292, 266); This.                                                                     Controls.AddRange (New system.windows.forms.control[]{                                                                     This.button2, This.button1,                                                                     This.textbox1,            This.picturebox1}); This.            Name = "Form1"; This.            Text = "Form1"; This. Load + = new System.EventHandler (this. Form1_loaD); This.         ResumeLayout (FALSE);         } #endregion Assembly _assembly;         Stream _imagestream;         StreamReader _textstreamreader;         <summary>//The main entry point for the application.         </summary> [STAThread] static void Main () {Application.Run (New Form1 ());               private void Form1_Load (object sender, System.EventArgs e) {try {               _assembly = assembly.getexecutingassembly (); _imagestream = _assembly.              GetManifestResourceStream ("MyNamespace.MyImage.bmp"); _textstreamreader = new StreamReader (_assembly.            GetManifestResourceStream ("MyNamespace.MyTextFile.txt"));            } catch {MessageBox.Show ("Error accessing resources!");       }} private void Button1_Click (object sender, System.EventArgs e) {try {        pictureBox1.Image = new Bitmap (_imagestream);            } catch {MessageBox.Show ("Error creating image!");               }} private void Button2_Click (object sender, System.EventArgs e) {try { if (_textstreamreader.peek ()! =-1) {TextBox1.Text = _textstreamreader.readline               ();            }} catch {MessageBox.Show ("Error writing text!"); }         }      }   }

note in Visual Studio 2005 or in Visual Studio 2008, you should change the code. When you create a Windows forms project, a form of Visual C # is added to the project by default. This form is named Form1. The two files that represent a form are called Form1.cs and Form1.designer.cs. Write your code in the Form1.cs. The Designer.cs file is a code implementation that is written by the Windows Forms Designer, and you execute it by adding controls. For more information about the Windows Forms Designer in Visual C # 2005 or Visual Studio 2008, visit the following Microsoft Web site:

Http://msdn2.microsoft.com/en-us/library/ms173077.aspx

Trouble shooting

Because resource names are case-sensitive, verify that you are using the appropriate spelling and capitalization access for the resource. You can use ILDASM to read the manifest's data to verify the exact spelling of the resource.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.