Uso de Visual C# para realizar E/S de archivos básicos

En este artículo se describe cómo realizar E/S de archivos básicas en Visual C# y se proporciona un ejemplo de código para ilustrar cómo realizar esta tarea.

Versión original del producto: Visual C#
Número de KB original: 304430

Resumen

Nota:

En este artículo paso a paso se muestra cómo realizar seis operaciones básicas de entrada y salida de archivos (E/S) en Visual C#. Si no está familiarizado con .NET Framework, verá que el modelo de objetos para las operaciones de archivos en .NET es similar al FileSystemObject (FSO) que es popular entre muchos desarrolladores de Visual Studio 6.0. Para facilitar la transición, la funcionalidad que se muestra en Cómo usar FileSystemObject con Visual Basic.

Todavía puede usar en FileSystemObject .NET. FileSystemObject Dado que es un componente del modelo de objetos de componente (COM), .NET requiere que el acceso al objeto sea a través de la capa de interoperabilidad. Microsoft .NET genera un contenedor para el componente si quiere usarlo. Sin embargo, las Fileclases , FileInfo, Directory, DirectoryInfo y otras clases relacionadas de .NET Framework ofrecen funcionalidad que no está disponible con FSO, sin la sobrecarga de la capa de interoperabilidad.

Operaciones de E/S de archivo demostradas

En los ejemplos de este artículo se describen las operaciones básicas de E/S de archivo. En la sección ejemplo paso a paso se describe cómo crear un programa de ejemplo que muestre las siguientes operaciones de E/S de archivo:

  • Leer un archivo de texto
  • Escribir un archivo de texto
  • Visualización de la información del archivo
  • Enumeración de unidades de disco
  • Enumerar carpetas
  • Enumerar archivos

Si desea usar los siguientes ejemplos de código directamente, tenga en cuenta lo siguiente:

  • Incluya el espacio de System.IO nombres, como se indica a continuación:

    using System.IO;
    
  • Declare la variable de la winDir siguiente manera:

    string winDir=System.Environment.GetEnvironmentVariable("windir");
    
  • La addListItem función se declara de la siguiente manera:

    private void addListItem(string value)
    {
        this.listBox1.Items.Add(value);
    }
    

    En lugar de declarar y usar la addListItem función , puede usar la siguiente instrucción directamente:

    this.listBox1.Items.Add(value);
    

Leer un archivo de texto

El código de ejemplo siguiente usa una StreamReader clase para leer el archivo System.ini . El contenido del archivo se agrega a un control ListBox. El try...catch bloque se usa para alertar al programa si el archivo está vacío. Hay muchas maneras de determinar cuándo se alcanza el final del archivo; en este ejemplo se usa el Peek método para examinar la siguiente línea antes de leerla.

StreamReader reader=new StreamReader(winDir + "\\system.ini");
try
{
    do
    {
        addListItem(reader.ReadLine());
    }
    while(reader.Peek()!= -1);
}
catch
{
    addListItem("File is empty");
}
finally
{
    reader.Close();
}

Escribir un archivo de texto

Este código de ejemplo usa una StreamWriter clase para crear y escribir en un archivo. Si tiene un archivo existente, puede abrirlo de la misma manera.

StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
writer.WriteLine("File created using StreamWriter class.");
writer.Close();
this.listbox1.Items.Clear();
addListItem("File Written to C:\\KBTest.txt");

Visualización de la información del archivo

Este código de ejemplo usa un FileInfo objeto para acceder a las propiedades de un archivo. Notepad.exe se usa en este ejemplo. Las propiedades aparecen en un control ListBox.

FileInfo FileProps =new FileInfo(winDir + "\\notepad.exe");
addListItem("File Name = " + FileProps.FullName);
addListItem("Creation Time = " + FileProps.CreationTime);
addListItem("Last Access Time = " + FileProps.LastAccessTime);
addListItem("Last Write TIme = " + FileProps.LastWriteTime);
addListItem("Size = " + FileProps.Length);
FileProps = null;

Enumeración de unidades de disco

Este código de ejemplo usa las Directory clases y Drive para enumerar las unidades lógicas de un sistema. En este ejemplo, los resultados aparecen en un control ListBox.

string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
    addListItem(drive);
}

Enumerar subcarpetas

Este código de ejemplo usa el GetDirectories método de la Directory clase para obtener una lista de carpetas.

string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
    addListItem(dir);
}

Enumerar archivos

Este código de ejemplo usa el GetFiles método de la Directory clase para obtener una lista de archivos.

string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
    addListItem(i);
}

Muchas cosas pueden salir mal cuando un usuario obtiene acceso a los archivos. Es posible que los archivos no existan, que los archivos estén en uso o que los usuarios no tengan derechos sobre los archivos o carpetas a los que están intentando acceder. Es importante tener en cuenta estas posibilidades al escribir código y controlar las excepciones que se pueden generar.

Ejemplo paso a paso

  1. En Visual C#, cree una nueva aplicación Windows Forms. De forma predeterminada, se crea Form1 .

  2. Abra la ventana de código de Form1 (Form1.cs).

  3. Elimine todo el código de la Form1.cs.

  4. Pegue el código siguiente en la ventana de Editor código subyacente.

    using System.Windows.Forms;
    using System.IO;
    
    namespace fso_cs
    {
        public partial class Form1 : Form
        {
            string winDir = System.Environment.GetEnvironmentVariable("windir");
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, System.EventArgs e)
            {
                //How to read a text file.
                //try...catch is to deal with a 0 byte file.
                this.listBox1.Items.Clear();
                StreamReader reader = new StreamReader(winDir + "\\system.ini");
                try
                {
                    do
                    {
                        addListItem(reader.ReadLine());
                    }
                    while (reader.Peek()!= -1);
                }
                catch
                {
                    addListItem("File is empty");
                }
                finally
                {
                    reader.Close();
                }
            }
    
            private void button2_Click(object sender, System.EventArgs e)
            {
                //Demonstrates how to create and write to a text file.
                StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
                writer.WriteLine("File created using StreamWriter class.");
                writer.Close();
                this.listBox1.Items.Clear();
                addListItem("File Written to C:\\KBTest.txt");
            }
    
            private void button3_Click(object sender, System.EventArgs e)
            {
                //How to retrieve file properties (example uses Notepad.exe).
                this.listBox1.Items.Clear();
                FileInfo FileProps = new FileInfo(winDir + "\\notepad.exe");
                addListItem("File Name = " + FileProps.FullName);
                addListItem("Creation Time = " + FileProps.CreationTime);
                addListItem("Last Access Time = " + FileProps.LastAccessTime);
                addListItem("Last Write TIme = " + FileProps.LastWriteTime);
                addListItem("Size = " + FileProps.Length);
                FileProps = null;
            }
    
            private void button4_Click(object sender, System.EventArgs e)
            {
                //Demonstrates how to obtain a list of disk drives.
                this.listBox1.Items.Clear();
                string[] drives = Directory.GetLogicalDrives();
                foreach (string drive in drives)
                {
                    addListItem(drive);
                }
            }
    
            private void button5_Click(object sender, System.EventArgs e)
            {
                //How to get a list of folders (example uses Windows folder). 
                this.listBox1.Items.Clear();
                string[] dirs = Directory.GetDirectories(winDir);
                foreach (string dir in dirs)
                {
                    addListItem(dir);
                }
            }
    
            private void button6_Click(object sender, System.EventArgs e)
            {
                //How to obtain list of files (example uses Windows folder).
                this.listBox1.Items.Clear();
                string[] files = Directory.GetFiles(winDir);
                foreach (string i in files)
                {
                    addListItem(i);
                }
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                this.button1.Text = "Read Text File";
                this.button2.Text = "Write Text File";
                this.button3.Text = "View File Information";
                this.button4.Text = "List Drives";
                this.button5.Text = "List Subfolders";
                this.button6.Text = "List Files";
            }
    
            private void addListItem(string value)
            {
                this.listBox1.Items.Add(value);
            }
        }
    }
    
  5. Abra la ventana de código de Form1.Designer. cs.

  6. Elimine todo el código de Form1.Designer. cs.

  7. Pegue el código siguiente en Form1.Designer. cs.

    namespace fso_cs
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (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.button1 = new System.Windows.Forms.Button();
                this.button2 = new System.Windows.Forms.Button();
                this.button3 = new System.Windows.Forms.Button();
                this.button4 = new System.Windows.Forms.Button();
                this.button5 = new System.Windows.Forms.Button();
                this.button6 = new System.Windows.Forms.Button();
                this.listBox1 = new System.Windows.Forms.ListBox();
                this.SuspendLayout();
    
                // button1
                this.button1.Location = new System.Drawing.Point(53, 30);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(112, 23);
                this.button1.TabIndex = 1;
                this.button1.Text = "button1";
                this.button1.Click += new System.EventHandler(this.button1_Click);
    
                // button2
                this.button2.Location = new System.Drawing.Point(53, 62);
                this.button2.Name = "button2";
                this.button2.Size = new System.Drawing.Size(112, 23);
                this.button2.TabIndex = 2;
                this.button2.Text = "button2";
                this.button2.Click += new System.EventHandler(this.button2_Click);
    
                // button3
                this.button3.Location = new System.Drawing.Point(53, 94);
                this.button3.Name = "button3";
                this.button3.Size = new System.Drawing.Size(112, 23);
                this.button3.TabIndex = 3;
                this.button3.Text = "button3";
                this.button3.Click += new System.EventHandler(this.button3_Click);
    
                // button4
                this.button4.Location = new System.Drawing.Point(53, 126);
                this.button4.Name = "button4";
                this.button4.Size = new System.Drawing.Size(112, 23);
                this.button4.TabIndex = 4;
                this.button4.Text = "button4";
                this.button4.Click += new System.EventHandler(this.button4_Click);
    
                // button5
                this.button5.Location = new System.Drawing.Point(53, 158);
                this.button5.Name = "button5";
                this.button5.Size = new System.Drawing.Size(112, 23);
                this.button5.TabIndex = 5;
                this.button5.Text = "button5";
                this.button5.Click += new System.EventHandler(this.button5_Click);
    
                // button6
                this.button6.Location = new System.Drawing.Point(53, 190);
                this.button6.Name = "button6";
                this.button6.Size = new System.Drawing.Size(112, 23);
                this.button6.TabIndex = 6;
                this.button6.Text = "button6";
                this.button6.Click += new System.EventHandler(this.button6_Click);
    
                // listBox1
                this.listBox1.FormattingEnabled = true;
                this.listBox1.Location = new System.Drawing.Point(204, 30);
                this.listBox1.Name = "listBox1";
                this.listBox1.Size = new System.Drawing.Size(270, 199);
                this.listBox1.TabIndex = 7;
    
                // Form1
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(525, 273);
                this.Controls.Add(this.button6);
                this.Controls.Add(this.button5);
                this.Controls.Add(this.button4);
                this.Controls.Add(this.button3);
                this.Controls.Add(this.button2);
                this.Controls.Add(this.button1);
                this.Controls.Add(this.listBox1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.Load += new System.EventHandler(this.Form1_Load);
                this.ResumeLayout(false);
            }
            #endregion
    
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.Button button2;
            private System.Windows.Forms.Button button3;
            private System.Windows.Forms.Button button4;
            private System.Windows.Forms.Button button5;
            private System.Windows.Forms.Button button6;
            private System.Windows.Forms.ListBox listBox1;
        }
    }
    
  8. De forma predeterminada, Visual C# agrega un formulario al proyecto al crear un proyecto de Windows Forms. Este formulario se denomina Form1. Los dos archivos de código fuente que representan el formulario se denominan Form1.cs y Form1.Designer. cs. El código se escribe en el archivo Form1.cs . El Windows Forms Designer escribe código generado por el diseñador en form1.Designer. archivo cs. El código de los pasos anteriores refleja esa organización.

  9. Presione F5 para compilar y, a continuación, ejecutar el programa. Haga clic en los botones para ver las diferentes acciones. Al ver el código de ejemplo, es posible que desee contraer el área denominada Windows Form Designer Código generado para ocultar este código.