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.
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.
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.
To add text files and image files to embed as resources into your project, follow these steps:
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.
Right-click the project name, click Add, then click Add New Item
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.
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.
Right-click the file text or bitmap and select Properties
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
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.
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;
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;
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();
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"));
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!");
}
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
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:
control to the form.
control to the form, and then change its Text property to Display image
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!"); }
event.
control to the form.
control to the form, and then change its Text property to Get text
, and then paste the following code into the event:
try { if(_textStreamReader.Peek() != -1) { textBox1.Text = _textStreamReader.ReadLine(); } } catch { MessageBox.Show("Error writing text!"); }
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!"); } } } }
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.
aspThe 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!