使用 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 中演示的功能。

你仍然可以在 FileSystemObject .NET 中使用。 FileSystemObject由于它是组件对象模型 (COM) 组件,因此 .NET 要求访问该对象是通过互操作层访问的。 Microsoft .NET 会为你生成组件的包装器(如果想要使用它)。 但是,File.NET Framework 中的 、FileInfo、、DirectoryDirectoryInfo类和其他相关类提供 FSO 不可用的功能,而无需互操作层的开销。

演示的文件 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 窗体应用程序。 默认情况下, 创建 Form1

  2. 打开 Form1Form1.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 窗体项目时,Visual C# 会将一个窗体添加到项目中。 此窗体名为 Form1。 表示表单的两个源代码文件命名 为Form1.csForm1.Designer.cs。 在Form1.cs文件中编写代码。 Windows 窗体设计器在Form1.Designer.cs文件中编写设计器生成的代码。 上述步骤中的代码反映了该组织。

  9. 按 F5 生成,然后运行程序。 单击这些按钮可查看不同的操作。 查看示例代码时,可能需要折叠名为 Windows 窗体设计器生成的代码 的区域以隐藏此代码。