Usar o Visual C# para fazer E/S de arquivo básico

Este artigo descreve como fazer e/S de arquivo básico no Visual C#e fornece um exemplo de código para ilustrar como executar essa tarefa.

Versão original do produto: Visual C#
Número original do KB: 304430

Resumo

Observação

Este artigo passo a passo mostra como fazer seis operações básicas de entrada/saída de arquivo (E/S) no Visual C#. Se você for novo no .NET Framework, descobrirá que o modelo de objeto para operações de arquivo no .NET é semelhante ao FileSystemObject (FSO) popular entre muitos desenvolvedores do Visual Studio 6.0. Para facilitar a transição, a funcionalidade demonstrada em How To Use FileSystemObject with Visual Basic.

Você ainda pode usar o FileSystemObject no .NET. Como o FileSystemObject é um componente COM (Component Object Model), o .NET exige que o acesso ao objeto seja por meio da camada Interop. O Microsoft .NET gera um wrapper para o componente para você se você quiser usá-lo. No entanto, as Fileclasses , FileInfo, Directory, DirectoryInfo e outras classes relacionadas no .NET Framework, oferecem funcionalidade que não está disponível com o FSO, sem a sobrecarga da camada Interop.

Operações de E/S de arquivo demonstradas

Os exemplos neste artigo descrevem operações básicas de E/S de arquivo. A seção Exemplo passo a passo descreve como criar um programa de exemplo que demonstre as seguintes operações de E/S do arquivo:

  • Ler um arquivo de texto
  • Gravar um arquivo de texto
  • Exibir informações de arquivo
  • Listar unidades de disco
  • Listar pastas
  • Listar arquivos

Se você quiser usar os seguintes exemplos de código diretamente, esteja ciente do seguinte:

  • Inclua o System.IO namespace da seguinte maneira:

    using System.IO;
    
  • Declare a variável da winDir seguinte maneira:

    string winDir=System.Environment.GetEnvironmentVariable("windir");
    
  • A addListItem função é declarada da seguinte maneira:

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

    Em vez de declarar e usar a addListItem função, você pode usar a seguinte instrução diretamente:

    this.listBox1.Items.Add(value);
    

Ler um arquivo de texto

O código de exemplo a seguir usa uma StreamReader classe para ler o arquivo System.ini . O conteúdo do arquivo é adicionado a um controle ListBox. O try...catch bloco é usado para alertar o programa se o arquivo estiver vazio. Há muitas maneiras de determinar quando o final do arquivo é atingido; este exemplo usa o Peek método para examinar a próxima linha antes de lê-la.

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

Gravar um arquivo de texto

Este código de exemplo usa uma StreamWriter classe para criar e gravar em um arquivo. Se você tiver um arquivo existente, poderá abri-lo da mesma maneira.

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");

Exibir informações de arquivo

Este código de exemplo usa um FileInfo objeto para acessar as propriedades de um arquivo. Notepad.exe é usado neste exemplo. As propriedades aparecem em um controle 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;

Listar unidades de disco

Este código de exemplo usa as Directory classes e Drive para listar as unidades lógicas em um sistema. Para este exemplo, os resultados aparecem em um controle ListBox.

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

Listar subpastas

Este código de exemplo usa o GetDirectories método da Directory classe para obter uma lista de pastas.

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

Listar arquivos

Este código de exemplo usa o GetFiles método da Directory classe para obter uma listagem de arquivos.

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

Muitas coisas podem dar errado quando um usuário obtém acesso aos arquivos. Os arquivos podem não existir, os arquivos podem estar em uso ou os usuários podem não ter direitos nos arquivos ou pastas que estão tentando acessar. É importante considerar essas possibilidades ao escrever código e lidar com as exceções que podem ser geradas.

Exemplo passo a passo

  1. No Visual C#, crie um novo aplicativo Windows Forms. Por padrão, o Form1 é criado.

  2. Abra a janela de código do Form1 (Form1.cs).

  3. Exclua todo o código no Form1.cs.

  4. Cole o código a seguir na janela Code-Behind Editor.

    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 a janela de código para Form1.Designer. cs.

  6. Exclua todo o código em Form1.Designer. cs.

  7. Cole o código a seguir em 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. Por padrão, o Visual C# adiciona um formulário ao projeto quando você cria um projeto Windows Forms. Esse formulário se chama Form1. Os dois arquivos de código-fonte que representam o formulário são nomeados Form1.cs e Form1.Designer. cs. Você grava seu código no arquivo Form1.cs . O Windows Forms Designer grava o código gerado pelo designer no Form1.Designer. arquivo cs. O código nas etapas anteriores reflete essa organização.

  9. Pressione F5 para compilar e execute o programa. Clique nos botões para exibir as diferentes ações. Ao exibir o código de exemplo, talvez você queira recolher a área chamada Formulário do Windows Designer Código Gerado para ocultar esse código.