本分步指南介绍如何在 Visual C# .NET 中执行六个基本的文件输入/输出 (I/O) 操作。如果您是第一次接触 .NET,会发现 .NET 中的文件操作对象模型与许多 Visual Studio 6.0 开发人员都很熟悉的
FileSystemObject (FSO) 非常相似。为了让您更容易过渡,本文演示的功能基于下面的 Microsoft 知识库文章:
186118
(http://support.microsoft.com/kb/186118/) 如何通过 Visual Basic 使用 FileSystemObject
在 .NET 中仍可使用
FileSystemObject。因为
FileSystemObject 是一个组件对象模型 (COM) 组件,所以 .NET 要求对该对象的访问必须通过 Interop 层。如果您要使用该组件,.NET 可为您生成该组件的包装。但是,如果不通过 Interop 层,FSO 将不具备 .NET 框架中的
File、
FileInfo、
Directory、
DirectoryInfo 类及其他相关类所提供的功能。
要求
下面列出了推荐使用的硬件、软件、网络基础结构以及所需的 Service Pack:
文件 I/O 操作示例
本文中的示例讲述基本的文件 I/O 操作。“分步示例”一节说明如何创建一个演示下列六种文件 I/O 操作的示例程序:
1 | 读取文本文件 |
2 | 写入文本文件 |
3 | 查看文件信息 |
4 | 列出磁盘驱动器 |
5 | 列出文件夹 |
6 | 列出文件 |
注意:如果要直接使用下列示例代码,要注意下列事项:
| 必须包括 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);
}
列出子文件夹
此示例代码使用
Directory 类的
GetDirectories 方法获取文件夹列表。
string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
addListItem(dir);
}
列出文件
此示例使用
Directory 类的
GetFiles 方法获取文件夹列表。
string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
addListItem(i);
}
用户访问文件时可能会出现多种错误。文件可能不存在、可能在使用中,或者用户对试图访问的文件夹中的文件无访问权限。在编写代码和处理可能产生的异常时,将这些可能性考虑在内是很重要的。
分步示例
1. | 在 Visual C# .NET 中,创建一个新的 Windows 应用程序。默认情况下会创建 Form1。 |
2. | 打开 Form1 的代码窗口。 |
3. | 删除“代码隐藏编辑器”中的所有代码。 |
| 将下面的代码粘贴到“代码隐藏编辑器”窗口中:using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace fso_cs
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
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;
string winDir=System.Environment.GetEnvironmentVariable("windir");
private System.Windows.Forms.ListBox listbox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support.
//
InitializeComponent();
//
// TO DO: Add any constructor code after InitializeComponent call.
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (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.listbox1 = new System.Windows.Forms.ListBox();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(216, 32);
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(216, 64);
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(216, 96);
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);
//
// listbox1
//
this.listbox1.Location = new System.Drawing.Point(24, 24);
this.listbox1.Name = "listbox1";
this.listbox1.Size = new System.Drawing.Size(176, 199);
this.listbox1.TabIndex = 0;
//
// button4
//
this.button4.Location = new System.Drawing.Point(216, 128);
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(216, 160);
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(216, 192);
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);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(360, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button6,
this.button5,
this.button4,
this.button3,
this.button2,
this.button1,
this.listbox1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
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 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 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 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 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 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 addListItem(string value)
{
this.listbox1.Items.Add(value);
}
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");
}
}
}
|
| 按 F5 键生成并运行该程序。单击各按钮可观察不同的操作。查看示例代码时,您可能希望将命名为“Windows Form Designer Generated Code”的区域“折叠”起来以隐藏此代码。 |