使用 Visual C# 执行基本文件 I/O
本文介绍如何在 Visual C# 中执行基本文件 I/O,并提供代码示例来说明如何执行此任务。
原始产品版本: Visual C#
原始 KB 编号: 304430
摘要
注意
- 有关本文的 Visual Basic .NET 版本,请参阅 如何在 Visual Basic 2005 或 Visual Basic .NET 中执行基本文件 I/O。
- 有关本文的 Visual C++ .NET 版本,请参阅 如何在 Visual C++ 或 Visual C++ .NET 中执行基本文件 I/O。
- 本文介绍了 Microsoft .NET Framework 类库命名空间
System.IO
和System.Collections
。
本文分步介绍如何在 Visual C# 中执行六个基本文件输入/输出 (I/O) 操作。 如果你不熟悉 .NET Framework,你会发现 .NET 中用于文件操作的对象模型类似于FileSystemObject
许多 Visual Studio 6.0 开发人员常用的 (FSO) 。 为了简化转换,请参阅 如何在 Visual Basic 中使用 FileSystemObject 中演示的功能。
仍可以在 .NET 中使用 FileSystemObject
。 FileSystemObject
由于 是 COM) 组件 (组件对象模型,因此 .NET 要求通过互操作层访问对象。 如果需要使用,Microsoft .NET 会为你生成组件包装器。 但是,File
.NET Framework中的 、FileInfo
、 Directory
DirectoryInfo
类和其他相关类提供 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;
列出磁盘驱动器
此示例代码使用 Directory
和 Drive
类列出系统上的逻辑驱动器。 对于此示例,结果显示在 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);
}
当用户获得对文件的访问权限时,许多事情都可能会出错。 这些文件可能不存在,文件可能正在使用中,或者用户可能没有他们尝试访问的文件或文件夹的权限。 在编写代码和处理可能生成的异常时,请务必考虑这些可能性。
分步示例
在 Visual C# 中,创建新的Windows 窗体应用程序。 默认情况下, 将创建 Form1 。
打开 Form1 (Form1.cs) 的代码窗口。
删除 Form1.cs中的所有代码。
将以下代码粘贴到“代码隐藏编辑器”窗口中。
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); } } }
打开 Form1.Designer 的代码窗口。cs.
删除 Form1.Designer 中的所有代码。cs.
将以下代码粘贴到 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; } }
默认情况下,在创建Windows 窗体项目时,Visual C# 会向项目添加一个窗体。 此窗体名为 Form1。 表示表单的两个源代码文件名为 Form1.cs 和 Form1.Designer。cs. 在 Form1.cs 文件中编写代码。 Windows 窗体 Designer在 Form1.Designer 中编写设计器生成的代码。cs 文件。 上述步骤中的代码反映了该组织。
按 F5 生成,然后运行程序。 单击按钮可查看不同的操作。 查看示例代码时,可能需要折叠名为“Windows 窗体”Designer“生成代码”的区域来隐藏此代码。
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈