Leer archivo de texto de recursos incrustados en C#
Este tutorial demuestra la lectura de archivos de texto de recursos incrustados mediante el lenguaje de programación C#.
Leer archivo de texto de recursos incrustados
Los archivos incrustados se conocen como recursos incrustados y puede acceder a estos archivos en tiempo de ejecución utilizando la clase Assembly ubicada en el espacio de nombres System.Reflection. Se puede crear un archivo incrustado a partir de cualquier archivo que actualmente forme parte del Proyecto.
Para leer un archivo de texto de recurso incrustado, debemos seguir los pasos a continuación:
-
Agregar carpeta y archivo
Primero, agregaremos una carpeta llamada
archivosal Proyecto. Luego, agregaremos el archivo incrustado dentro de esa carpeta utilizando la opciónAgregar -> Elemento existenteque se puede encontrar en elMenú contextualdelExplorador de soluciones, como se muestra a continuación.Nos permitirá añadir el archivo incrustado dentro de la carpeta.

Después de agregar los archivos que se van a incrustar, deberá hacer clic con el botón derecho en
Archivo, luego haga clic enPropiedades.
Ahora, siga la captura de pantalla a continuación para cambiar el valor del atributo
Build ActiondeContental recurso incrustado.
-
Crear formulario de Windows
Primero, agregue un
TextBoxal formulario de Windows y asígnele el nombretxtTextBoxde susPropiedades.
Ahora, agregue un botón llamado
btnTexty muestre el textoRead Embed Texten el botón como se muestra a continuación:
-
Escribir código de formulario de Windows
Primero, tenemos que importar las siguientes bibliotecas:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Reflection;Al hacer clic con el botón derecho en el botón
Leer texto incrustadopara crear su evento, aquí, escribiremos el código del botón de la siguiente manera:
Crearemos un objeto de método
Asambleallamadoensamblaje:var asmbly = Assembly.GetExecutingAssembly();Luego, crearemos una variable de tipo
varllamadafilepath. Esta variable contendrá la ruta del archivo de texto.var filePath = "ReadEmbedTextbyZeeshan.files.Shani.txt";Por último, mostraremos el texto del archivo incrustado usando
StreamReader, que leerá un archivo de texto de la ruta dada.using (Stream s = asmbly.GetManifestResourceStream(filePath)) using ( StreamReader sr = new StreamReader(s)) { txtTextBox.Text = sr.ReadToEnd(); } -
Código fuente completo
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Reflection; namespace ReadEmbedTextbyZeeshan { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnText_Click(object sender, EventArgs e) { var asmbly = Assembly.GetExecutingAssembly(); var filePath = "ReadEmbedTextbyZeeshan.files.Shani.txt"; using (Stream s = asmbly.GetManifestResourceStream(filePath)) using ( StreamReader sr = new StreamReader(s)) { txtTextBox.Text = sr.ReadToEnd(); } } } }Cuando hacemos clic en el botón
Leer texto incrustado, mostrará el siguiente resultado:Producción:

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.
LinkedIn