HOW TO:在 Visual C++ .NET 中执行基本的文件 I/O

本文的发布号曾为 CHS307398
有关本文的 Microsoft Visual C# .NET 版本,请参见 304430
有关本文的 Microsoft Visual Basic .NET 版本,请参见 304427
本文引用下面的 Microsoft .NET 框架类库名称空间:
  • System.ComponentModel
  • System.Windows.Forms
  • System.Drawing

本任务的内容

概要
本分步指南介绍如何在 Visual C++ .NET 中执行六个基本的文件输入/输出 (I/O) 操作。如果是第一次接触 .NET,您会发现 .NET 中的文件操作对象模型与许多 Visual Studio 6.0 开发人员都很熟悉的 FileSystemObject (FSO) 非常相似。为了让您更容易过渡,本文演示的功能基于以下 Microsoft 知识库文章:
  • 186118 HOWTO: Use FileSystemObject with Visual Basic(HOWTO:在 Visual Basic 中使用 FileSystemObject)
在 .NET 中仍可以使用 FileSystemObject。因为 FileSystemObject 是一个"部件对象模型 (COM)"组件,所以 .NET 要求对该对象的访问必须通过 Interop 层。如果您要使用该组件,.NET 可为您生成该组件的包装。但是,FileFileInfoDirectoryDirectoryInfo 类及 .NET Framework 中其他相关类将提供 FSO 不具备的功能,而没有 Interop 层的系统开销。

返回页首

要求

下面的列表简要列出了推荐使用的硬件、软件、网络结构以及所需的 Service Pack:
  • Visual C++ .NET
返回页首

所演示的文件 I/O 操作

本文中的示例介绍了基本的文件 I/O 操作。"分步示例"一节说明如何创建一个演示下列六种文件 I/O 操作的示例应用程序:
  • 读取文本文件
  • 写入文本文件
  • 查看文件信息
  • 列出磁盘驱动器
  • 列出文件夹
  • 列出文件
返回页首

读取文本文件

下面的代码示例使用 StreamReader 类读取 System.ini 文件。该文件的内容被添加到一个 ListBox 控件中。其中的 try...catch 块用于在文件为空时向程序发出警报。有多种方法可确定是何时到达文件结尾;本示例使用了 Peek 方法在读取下一行之前先检验该行。
listbox1->Items->Clear();	try	{    		String* textFile = String::Concat(windir,                                    (S"\\mytest.txt")); 	        StreamReader *reader=new  StreamReader(textFile);		do		{		    listbox1->Items->Add(reader->ReadLine());		}   		while(reader->Peek() != -1);	}               	catch (System::Exception *e)	{ 		listbox1->Items->Add(e);	}}
返回页首

写入文本文件

此代码示例使用 StreamWriter 类创建一个文件并向其中写入。如果已有一个现有文件,则可以用同样的方式打开它。
StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");pwriter->WriteLine(S"File created using StreamWriter class.");pwriter->Close();listbox1->Items->Clear();String *filew = new String(S"File Written to C:\\KBTest.txt");listbox1->Items->Add(filew);
返回页首

查看文件信息

此代码示例使用 FileInfo 类来访问文件的属性。此示例中使用了 Notepad.exe。这些属性显示在 ListBox 控件中。
listbox1->Items->Clear();String* testfile = String::Concat(windir, (S"\\notepad.exe")); FileInfo *pFileProps  =new FileInfo(testfile);listbox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName() )) );listbox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Last Access Time = "  ,(pFileProps->get_LastAccessTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length() ).ToString()) );
返回页首

列出磁盘驱动器

此代码示例使用 DirectoryDrive 两个类来列出系统上的逻辑驱动器。例如,该示例的结果显示在 ListBox 控件中。
listbox1->Items->Clear();String* drives[] = Directory::GetLogicalDrives();int numDrives = drives->get_Length();for (int i=0; i<numDrives; i++)  {	listbox1->Items->Add(drives[i]);  } 
返回页首

列出子文件夹

此代码示例使用 Directory 类的 GetDirectories 方法获取文件夹列表。
listbox1->Items->Clear();String* dirs[] = Directory::GetDirectories(windir);int numDirs = dirs->get_Length();for (int i=0; i<numDirs; i++){listbox1->Items->Add(dirs[i]);}
返回页首

列出文件

此代码示例使用 Directory 类的 GetFiles 方法获取文件列表。
listbox1->Items->Clear();String* files[]= Directory::GetFiles(this->windir);int numFiles = files->get_Length();for (int i=0; i<numFiles; i++){listbox1->Items->Add(files[i]);}
用户访问文件时可能会出现多种错误。文件可能会不存在、可能在使用中,或者用户对试图访问的文件夹中的文件无访问权限。重要的是,在编写代码时将这些可能性考虑在内,并处理可能产生的异常。

返回页首

分步示例

  1. 在 Visual C++ .NET 中,新建一个 C++ 应用程序托管扩展(单击选择托管的 C++ 应用程序图标)。将该项目命名为 Q307398。
  2. 打开 Q307398.cpp 的代码窗口。
  3. 删除全部代码。
  4. 将下列代码粘贴到 Q307398.cpp 中:
    #using <mscorlib.dll>using namespace System;using namespace System::IO;// required dlls for WinForms#using "System.dll"#using "System.Windows.Forms.dll"#using "System.Drawing.dll"// required namespaces for WinFormsusing namespace System::ComponentModel;using namespace System::Windows::Forms;using namespace System::Drawing;__gc class WinForm:public Form {private:			Button	    *button1;	Button	    *button2;	Button	    *button3;	Button	    *button4;	Button	    *button5;	Button	    *button6;	String*     windir;	ListBox     *listbox1;	String	    *caption;	// Caption of the WinForm	int	    width;		// width of the WinForm	int	    height;		// height of the WinFormpublic:	WinForm() 	{		// Set caption and size of the WinForm		caption = "Form1";		width = 360;		height = 273;		windir=System::Environment::GetEnvironmentVariable("windir");		InitForm();	}	void Dispose()	{	// Form is being destroyed.Do any clean-up that you have to do here.		Form::Dispose();	}void InitForm(){		// Setup controls here		// Basic WinForm Settings			SuspendLayout();		// button1		// button1 = new Button();		button1->Text = "button1";		button1->Name = "button1";		button1->Size = Drawing::Size(112, 23);		button1->TabIndex = 1;		button1->Location = Drawing::Point(216.32);		button1->Click += (new EventHandler(this,                                       &WinForm::button1_Click));		Controls->Add(button1);		// button2		// 		button2 = new Button();		button2->Text = "button2";		button2->Name = "button2";		button2->Size = Drawing::Size(112, 23);		button2->TabIndex = 2;		button2->Location = Drawing::Point(216.64);		button2->Click += (new EventHandler(this,                                   &WinForm::button2_Click));		Controls->Add(button2);				// button3		// 		button3 = new Button();		button3->Text = "button3";		button3->Name = "button3";		button3->Size = Drawing::Size(112, 23);		button3->TabIndex = 3;		button3->Location = Drawing::Point(216.96);		button3->Click += (new EventHandler(this,                                   &WinForm::button3_Click));		Controls->Add(button3);		// listbox1		// 		listbox1 = new ListBox();		listbox1->Text = "Listbox1";		listbox1->Name = "Listbox1";		listbox1->Size = Drawing::Size(176, 199);		listbox1->TabIndex = 0;		listbox1->Location = Drawing::Point(24,24);		Controls->Add(listbox1);					// 		// button4		// 		button4 = new Button();		button4->Text = "button4";		button4->Name = "button4";		button4->Size = Drawing::Size(112, 23);		button4->TabIndex = 4;		button4->Location = Drawing::Point(216,128);		button4->Click += (new EventHandler(this,                                    &WinForm::button4_Click));		Controls->Add(button4);		// button5		// 		button5 = new Button();		button5->Text = "button5";		button5->Name = "button5";		button5->Size = Drawing::Size(112, 23);		button5->TabIndex = 5;		button5->Location = Drawing::Point(216,160);		button5->Click += (new EventHandler(this,                                   &WinForm::button5_Click));		Controls->Add(button5);		// button6		// 		button6 = new Button();		button6->Text = "button6";		button6->Name = "button6";		button6->Size = Drawing::Size(112, 23);		button6->TabIndex = 6;		button5->Location = Drawing::Point(216,192);		button6->Click += (new EventHandler(this,                                   &WinForm::button6_Click));		Controls->Add(button6);		Text = caption;		Size = System::Drawing::Size(width, height);			Name = "Form1";		Text = "Form1";		Load += new System::EventHandler(this, Form1_Load);		ResumeLayout(false);}void button6_Click(Object *sender, EventArgs *e){//how to obtain list of files (example uses Windows folder)	listbox1->Items->Clear();	String* files[]= Directory::GetFiles(this->windir);	int numFiles = files->get_Length();	for (int i=0; i<numFiles; i++)	{	 listbox1->Items->Add(files[i]);	}}void button1_Click(Object *sender, EventArgs *e){//how to read a text file//try...catch is to deal with a 0 byte file or non-existant file	listbox1->Items->Clear();   	try	{    	    String* textFile = String::Concat(windir,                                             ("\\mytest.txt")); 	    StreamReader *reader=new  StreamReader(textFile);	    do	    {		listbox1->Items->Add(reader->ReadLine());	    }   	    while(reader->Peek() != -1);	}               	catch (System::Exception *e)	{ 	    listbox1->Items->Add(e);	}}void Form1_Load(Object *sender, EventArgs *e){	button1->Text = "Read Text File";	button2->Text = "Write Text File";	button3->Text = "View File Information";	button4->Text = "List Drives";	button5->Text = "List Subfolders";	button6->Text = "List Files";}void button5_Click(Object *sender, EventArgs *e){         //how to get a list of folders (example uses Windows folder) 	listbox1->Items->Clear();	String* dirs[] = Directory::GetDirectories(windir);	int numDirs = dirs->get_Length();	for (int i=0; i<numDirs; i++)	{		listbox1->Items->Add(dirs[i]);                                                      	}}void button4_Click(Object *sender, EventArgs *e){//demonstrates  how to obtain a list of disk drives	listbox1->Items->Clear();	String* drives[] = Directory::GetLogicalDrives();	int numDrives = drives->get_Length();	for (int i=0; i<numDrives; i++)	{		listbox1->Items->Add(drives[i]);	}}void button3_Click(Object *sender, EventArgs *e){   //how to retrieve file properties (example uses notepad.exe)listbox1->Items->Clear();String* testfile = String::Concat(windir, (S"\\notepad.exe")); FileInfo *pFileProps  =new FileInfo(testfile);listbox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName() )) );listbox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Last Access Time = "  ,(pFileProps->get_LastAccessTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime() ).ToString()) );listbox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length() ).ToString()) );}      void button2_Click(Object *sender, EventArgs *e){//demonstrates how to create and write to a text fileStreamWriter* pwriter = new StreamWriter("c:\\KBTest.txt");pwriter->WriteLine("File created using StreamWriter class.");pwriter->Close();listbox1->Items->Clear();String *filew = new String(S"File Written to C:\\KBTest.txt");listbox1->Items->Add(filew);}};void main(){	// This line creates an instance of WinForm, and 	// uses it as the Main Window of the application. 	Application::Run(new WinForm());}
  5. 在"解决方案资源管理器"中右键单击该项目名称,然后单击属性。单击选择 C/C++,然后单击预编译头。将设置从创建/使用预编译头更改为不使用预编译头,然后保存项目。
  6. 按 F5 键生成并运行该程序。单击这些按钮观察不同的操作。
返回页首
参考
有关其他点击率最高的 Visual C++ .NET Microsoft 知识库文章,请访问以下 Microsoft Web 站点:有关 Visual C++ .NET 的更多一般信息,请访问下面的 Microsoft Usenet 新闻组:有关在 Visual C++ 的托管扩展中创建 Windows 窗体的更多信息,请参见 Visual Studio .NET 帮助中的示例"ManagedCWinFormWiz"。

返回页首
属性

文章 ID:307398 - 上次审阅时间:08/13/2002 14:50:00 - 修订版本: 1.0

Microsoft Visual C++ .NET 2002 标准版

  • kbhowto kbhowtomaster kbnewsgrouplink KB307398
反馈