Używanie języka Visual C# do wykonywania podstawowych operacji we/wy plików

W tym artykule opisano sposób wykonywania podstawowych operacji we/wy plików w języku Visual C#, a także przedstawiono przykład kodu ilustrujący sposób wykonywania tego zadania.

Oryginalna wersja produktu: Visual C#
Oryginalny numer KB: 304430

Podsumowanie

Uwaga

W tym artykule krok po kroku pokazano, jak wykonać sześć podstawowych operacji wejścia/wyjścia pliku (We/Wy) w języku Visual C#. Jeśli dopiero zaczynasz korzystać z .NET Framework, okaże się, że model obiektów dla operacji na plikach na platformie .NET jest podobny do FileSystemObject modelu (FSO), który jest popularny wśród wielu deweloperów programu Visual Studio 6.0. Aby ułatwić przejście, funkcja przedstawiona w temacie How to Use FileSystemObject with Visual Basic (Jak używać elementu FileSystemObject w języku Visual Basic).

Nadal można używać elementu w programie FileSystemObject .NET. FileSystemObject Ponieważ element jest składnikiem modelu obiektów składników (COM), platforma .NET wymaga, aby dostęp do obiektu odbywał się za pośrednictwem warstwy Międzyoperacyjnej. Platforma Microsoft .NET generuje otokę dla składnika, jeśli chcesz jej używać. Jednak Fileklasy , FileInfo, DirectoryDirectoryInfo i inne powiązane klasy w .NET Framework oferują funkcje, które nie są dostępne w ramach logowania FSO, bez narzutu warstwy Międzyoperacyjnej.

Zademonstrowane operacje we/wy plików

W przykładach w tym artykule opisano podstawowe operacje we/wy plików. W sekcji przykładowej krok po kroku opisano sposób tworzenia przykładowego programu, który demonstruje następujące operacje we/wy pliku:

  • Odczytywanie pliku tekstowego
  • Pisanie pliku tekstowego
  • Wyświetlanie informacji o pliku
  • Wyświetlanie listy dysków
  • Foldery listy
  • Wyświetlanie listy plików

Jeśli chcesz bezpośrednio użyć następujących przykładów kodu, pamiętaj o następujących kwestiach:

  • Uwzględnij przestrzeń nazw w System.IO następujący sposób:

    using System.IO;
    
  • Zadeklaruj zmienną w winDir następujący sposób:

    string winDir=System.Environment.GetEnvironmentVariable("windir");
    
  • Funkcja addListItem jest zadeklarowana w następujący sposób:

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

    Zamiast deklarować i używać addListItem funkcji, można bezpośrednio użyć następującej instrukcji:

    this.listBox1.Items.Add(value);
    

Odczytywanie pliku tekstowego

Poniższy przykładowy kod używa StreamReader klasy do odczytu pliku System.ini . Zawartość pliku jest dodawana do kontrolki ListBox. Blok try...catch jest używany do powiadamiania programu, jeśli plik jest pusty. Istnieje wiele sposobów, aby określić, kiedy zostanie osiągnięty koniec pliku; W tym przykładzie użyto Peek metody do zbadania następnego wiersza przed odczytem.

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

Pisanie pliku tekstowego

Ten przykładowy kod używa StreamWriter klasy do tworzenia i zapisywania w pliku. Jeśli masz istniejący plik, możesz otworzyć go w ten sam sposób.

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

Wyświetlanie informacji o pliku

Ten przykładowy kod używa obiektu FileInfo do uzyskiwania dostępu do właściwości pliku. Notepad.exe jest używany w tym przykładzie. Właściwości są wyświetlane w kontrolce 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;

Wyświetlanie listy dysków

Ten przykładowy Directory kod używa klas i Drive do wyświetlania listy dysków logicznych w systemie. W tym przykładzie wyniki są wyświetlane w kontrolce ListBox.

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

Wyświetl listę folderów podrzędnych

Ten przykładowy GetDirectories kod używa metody klasy w Directory celu uzyskania listy folderów.

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

Wyświetlanie listy plików

Ten przykładowy GetFiles kod używa metody klasy w Directory celu uzyskania listy plików.

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

Wiele rzeczy może pójść nie tak, gdy użytkownik uzyska dostęp do plików. Pliki mogą nie istnieć, pliki mogą być używane lub użytkownicy mogą nie mieć praw do plików lub folderów, do których próbują uzyskać dostęp. Należy wziąć pod uwagę te możliwości podczas pisania kodu i obsługiwać wyjątki, które mogą zostać wygenerowane.

Przykład krok po kroku

  1. W języku Visual C# utwórz nową aplikację Windows Forms. Domyślnie tworzony jest formularz Form1 .

  2. Otwórz okno kodu formularza Form1 (Form1.cs).

  3. Usuń cały kod w Form1.cs.

  4. Wklej następujący kod w oknie Redaktor Code-Behind.

    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. Otwórz okno kodu dla pliku Form1.Projektant. cs.

  6. Usuń cały kod w pliku Form1.Projektant. cs.

  7. Wklej następujący kod w pliku Form1.Projektant. 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. Domyślnie program Visual C# dodaje jeden formularz do projektu podczas tworzenia projektu Windows Forms. Ten formularz nosi nazwę Form1. Dwa pliki kodu źródłowego reprezentujące formularz mają nazwę Form1.cs i Form1.Projektant. cs. Kod jest zapisywany w pliku Form1.cs . Windows Forms Projektant zapisuje kod wygenerowany przez projektanta w pliku Form1.Projektant. plik cs. Kod w poprzednich krokach odzwierciedla tę organizację.

  9. Naciśnij klawisz F5, aby skompilować, a następnie uruchomić program. Kliknij przyciski, aby wyświetlić różne akcje. Podczas wyświetlania przykładowego kodu można zwinąć obszar o nazwie Formularz systemu Windows Projektant Wygenerowany kod, aby ukryć ten kod.