本文的发布号曾为 CHS304430
概要
本文中列出的分步过程演示了如何在 Visual C# .NET 中进行六种基本的文件输入/输出 (I/O) 操作。如果是第一次接触 .NET,您会发现 .NET 中的文件操作对象模型与许多 Visual Studio 6.0 开发人员都很熟悉的 FileSystemObject (FSO) 非常相似。为了让您过渡更容易,本文演示的功能基于以下 Microsoft 知识库文章:186118 HOWTO: Use FileSystemObject with Visual Basic(在 Visual Basic 中使用 FileSystemObject)
在 .NET 中仍可以使用 FileSystemObject。因为 FileSystemObject 是一个“组件对象模型 (COM)”组件,所以 .NET 要求对该对象的访问必须通过 Interop 层。如果您选择使用该组件,.NET 将为其生成一个包装。但是,如果不通过 Interop 层,FSO 将不具备 .NET 框架中的 File、 FileInfo、 Directory 和 DirectoryInfo 类及其他相关类所提供的功能。返回页首
要求
下面列出推荐使用的硬件、软件、网络结构以及所需的 Service Pack:- Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server 或 Windows NT 4.0 Server
- Microsoft Visual Studio .NET
- Microsoft Visual Studio .NET 软件开发工具包 (SDK) 快速入门
讨论所演示的文件 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); }返回页首
列出子文件夹
此代码示例使用 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); }用户访问文件时可能会出现多种错误。例如,文件可能会不存在、可能在使用中,或者用户对试图访问的文件夹中的文件无访问权限。在编写代码和处理可能产生的异常时,将这些可能性考虑在内是很重要的。
返回页首
分步示例
- 在 Visual C# .NET 中,启动一个新的 Windows 应用程序。默认情况下创建 Form1。
- 打开 Form1 的代码窗口。
- 删除“代码隐藏编辑器”中的所有代码。
- 将下面的代码粘贴到“代码隐藏编辑器”窗口中。
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”的区域“折叠”起来以隐藏此代码。
这篇文章中的信息适用于:
- Microsoft Visual C# .NET (2002)
最近更新: | 2002-2-15 (1.0) |
关键字 | kbhowto kbHOWTOmaster KB304430 |