Table of Contents
Overview
Step-by-Step Demonstration
Add embedded resources
Accessing Resources
This example uses two
Due to resources Names are case-sensitive, please verify that you are accessing the resource using the appropriate spelling and case. You can use ILDASM to read the manifest's data to verify the exact spelling of a resource.
Home Backend Development C#.Net Tutorial Detailed explanation of how to embed and use C# to access resource code

Detailed explanation of how to embed and use C# to access resource code

Mar 14, 2017 pm 01:54 PM

How to use embedded resources in

C#?

This step-by-step guide shows you how to use C# to embed a resource as part of an assembly and then access the resource at runtime.

Overview

The .NET Framework can encapsulate files as part of a compiled assembly. These files are called embedded resources. These resources are completely independent assemblies associated with .resources and .resx files. You can access these resources at runtime through the Assembly classes in the System.Reflectionnamespace.

The main advantage of embedded manifest resources is that because these files are part of the compiled assembly, users cannot accidentally delete or mistakenly put them into your application, which in some cases The presence of vital files may prevent the execution of the program. 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 include files that will not change during the lifetime of the application as embedded resources.

Step-by-Step Demonstration

To add embedded resources to your project, you must first add these files as part of your project. After adding the file to the project, you can access and display resources in the System.Reflection namespace.

Add embedded resources

To add text files and image files to embed as resources into your project, follow these steps:

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

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

  3. In the New Project dialog box, from the menu, select Text File and name the file MyTextFile.txt. 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 a 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 contents are 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 property. By default, this property is set to content. Please click the property and change the Build Action property to Embedded Resource

  7. Repeat steps 4 and 5 for the other file.

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

Please note: Resource file names are case-sensitive. When accessing resources, you must use the exact spelling and case of the file name. If you do not use the exact spelling and case of the filename, the method call to access ManifestResourceStream returns does nothing , and the system does not raise abnormal.

Note: If you want to verify these resource names, you can use the Microsoft Intermediate Language Disassembler (ILDASM) to view the manifest data, which lists the included resources.

Accessing Resources

To access resources that have been embedded in your assembly's manifest, import System.IO and System.Reflection namespace, as follows:

   using System.IO;
   using System.Reflection;				
Copy after login

System.IO The namespace provides the definition of the stream and the methods of the class provided by the assembly defined in the System.Reflection namespace to Access resources embedded in the assembly.
Read resources from the assembly when the form is loaded when declared in the following general declaration area:

   Assembly _assembly;
   Stream _imageStream;
   StreamReader _textStreamReader;				
Copy after login

Note: To access in code# For the Load event of the form in ##Editor, please double-click the form in the design editor. To read resources from an assembly that is executing the current code, you must obtain an instance of that assembly. To do this, use the assembly's
GetExecutingAssembly
method, as follows:

   _assembly = Assembly.GetExecutingAssembly();				
Copy after login
Read information from a resource into a stream, the

GetManifestResourceStream

method Call execution. The parameter passed to this method is the name of the resource to be accessed. Execute the Load event of the form, and then read the two resources into their corresponding streams.

   _imageStream = _assembly.GetManifestResourceStream("MyNameSpace.MyImage.bmp");
   _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNameSpace.MyTextFile.txt"));				
Copy after login
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!");
   }				
Copy after login

Try-catch

statement, called in .NET In, structured error handling is used to capture any errors that may occur when an instance of the assembly class accesses a resource.

Display Resources

This example uses two

buttons

to display embedded resources. When the first button is clicked, a bitmap image based on the resource read from the assembly is created and displayed in the PictureboxControls of the form . The second button's text resource is read from and the text displayed in the text box. To display embedded resources, perform the following steps:

    Add the
  1. Picture Box

    control to the form.

  2. Add a new
  3. Button

    control to the form, and then change its Text property to Display image

  4. Double-click the button to open its
  5. Click

    event in the code viewer, then paste the following code in this case:

       try
       {
          pictureBox1.Image = new Bitmap(_imageStream);			       }
       catch 
       {
          MessageBox.Show("Error creating image!");
       }					
    Copy after login
  6. This code generates a new instance based on the bitmap of the resource stream read in the form's
  7. Load

    event.

  8. #Add a
  9. TextBox

    control to the form.

  10. Add another
  11. Button

    control to the form, and then change its Text property to Get text

  12. Double-click the button in the Design Editor to open
  13. Click_Event

    , and then paste the following code into the event:

       try
       {
          if(_textStreamReader.Peek() != -1)
          {
             textBox1.Text = _textStreamReader.ReadLine();
          }
       }
       catch
       {
          MessageBox.Show("Error writing text!");
       }					
    Copy after login
  14. This code determines whether the character to be read is still present in the stream. If the character is found, the text box will read the line.


  15. #Press the F5 key to run the application.
  16. Full 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.PictureBox 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 support - 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!");
            }		
         }
      }
   }				
Copy after login

Note

The code should be changed if you are in Visual Studio 2005 or in Visual Studio 2008. When you create a Windows Forms project, Visual C# adds a form to the project by default. This form is named Form1. The two files representing the form are called Form1.cs and Form1.designer.cs. Write your code in Form1.cs. The Designer.cs file is the code written by the Windows Forms Designer that implements all the actions that you perform by adding controls. For more information about Windows Forms Designer in Visual C# 2005 or Visual Studio 2008, visit Microsoft below Web site: http://msdn2.microsoft.com/en-us/library/ms173077.

asp

xTroubleshooting

Due to resources Names are case-sensitive, please verify that you are accessing the resource using the appropriate spelling and case. You can use ILDASM to read the manifest's data to verify the exact spelling of a resource.


The above is the detailed content of Detailed explanation of how to embed and use C# to access resource code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles