使用 Visual C# 執行基本檔案 I/O

本文說明如何在 Visual C# 中執行基本檔案 I/O,並提供程式碼範例以說明如何執行這項工作。

原始產品版本: Visual C#
原始 KB 編號: 304430

摘要

注意事項

本逐步文章說明如何在 Visual C# 中執行六個基本檔案輸入/輸出 (I/O) 作業。 如果您不熟悉 .NET Framework,您會發現 .NET 中檔案作業的物件模型類似於FileSystemObject許多Visual Studio 6.0 開發人員常用的 (FSO) 。 若要簡化轉換,請參閱 如何搭配 Visual Basic 使用 FileSystemObject 中示範的功能。

您仍然可以在 .NET 中使用 FileSystemObjectFileSystemObject因為 是元件物件模型 (COM) 元件,所以 .NET 需要透過 Interop 層存取物件。 如果您想要使用該元件,Microsoft .NET 會為您產生包裝函式。 不過,.NET Framework 中的 FileDirectoryFileInfo、、DirectoryInfo類別和其他相關類別,會提供 FSO 無法使用的功能,而不需要 Interop 層的額外負荷。

示範的檔案 I/O 作業

本文中的範例說明基本檔案 I/O 作業。 逐步範例一節說明如何建立示範下列檔案 I/O 作業的範例程式:

  • 讀取文字檔
  • 撰寫文字檔
  • 檢視檔案資訊
  • 列出磁碟驅動器
  • 列出資料夾
  • 列出檔案

如果您要直接使用下列程式代碼範例,請注意下列事項:

  • System.IO包含命名空間,如下所示:

    using System.IO;
    
  • 宣告變數, winDir 如下所示:

    string winDir=System.Environment.GetEnvironmentVariable("windir");
    
  • addListItem 式的宣告如下:

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

    您可以直接使用下列語句,而不是宣告和使用 addListItem 函式:

    this.listBox1.Items.Add(value);
    

讀取文字檔

下列範例程式代碼會使用 StreamReader 類別來讀 取System.ini 檔案。 檔案的內容會新增至 ListBox 控制件。 如果 try...catch 檔案是空的,則會使用 區塊來警示程式。 有許多方法可以判斷何時到達檔尾;這個範例會使用 Peek 方法來檢查下一行,然後再讀取它。

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

撰寫文字檔

此範例程式代碼會使用 StreamWriter 類別來建立和寫入檔案。 如果您有現有的檔案,可以用相同方式開啟它。

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

檢視檔案資訊

此範例程式代碼會使用 FileInfo 物件來存取檔案的屬性。 此範例中會使用 Notepad.exe。 屬性會出現在 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;

列出磁碟驅動器

此範例程式代碼會使用 DirectoryDrive 類別來列出系統上的邏輯磁碟驅動器。 在此範例中,結果會出現在 ListBox 控制件中。

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

列出子資料夾

此範例程式代碼會使用 GetDirectories 類別的 Directory 方法來取得資料夾清單。

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

列出檔案

此範例程式代碼會使用 GetFiles 類別的 Directory 方法來取得檔案清單。

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

當使用者取得檔案的存取權時,可能會發生許多錯誤。 檔案可能不存在、檔案可能正在使用中,或使用者可能沒有他們嘗試存取之檔案或資料夾的許可權。 當您撰寫程式代碼並處理可能產生的例外狀況時,請務必考慮這些可能性。

逐步範例

  1. 在 Visual C# 中,建立新的 Windows Forms 應用程式。 根據預設, 會建立 Form1

  2. 開啟 Form1 (Form1.cs ) 的程式代碼視窗。

  3. 刪除Form1.cs中的所有 程序代碼。

  4. 在 [程序代碼後置] 編輯器 視窗中貼上下列程序代碼。

    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. 開啟 Form1.Designer 的程式代碼視窗。cs

  6. 刪除 Form1.Designer 中的所有程式代碼。cs

  7. 在 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. 根據預設,當您建立 Windows Forms 專案時,Visual C# 會將一個表單新增至專案。 此表單名為 Form1。 代表表單的兩個原始程式碼檔案名為 Form1.csForm1.Designer。cs。 您可以在 Form1.cs 檔案中撰寫程式代碼。 Windows Forms Designer 會在 Form1.Designer 中寫入設計工具產生的程式代碼。cs 檔案。 上述步驟中的程式代碼會反映該組織。

  9. 按 F5 建置,然後執行程式。 按兩下按鈕以檢視不同的動作。 當您檢視範例程式代碼時,您可能會想要折疊名為 Windows Form 的區域 Designer 產生的程式代碼來隱藏此程式碼。