HOW TO:在 Visual C++ .NET 進行基本的檔案 I/O

文章翻譯 文章翻譯
文章編號: 307398 - 檢視此文章適用的產品。
全部展開 | 全部摺疊

在此頁中

結論

本文將逐步說明如何在 Microsoft Visual C++ .NET 進行 6 種基本檔案輸出/輸入 (I/O) 作業。如果對 .NET Framework 並不熟悉,您將會發現在 .NET Framework 中檔案作業的物件模型,類似許多 Microsoft Visual Studio 6.0 開發人員常使用的 FileSystemObject (FSO)。為了使轉換更為容易,本文所示範的功能都是根據下列「Microsoft 知識庫」文件:
186118 HOWTO:將 FileSystemObject 與 Visual Basic 搭配使用
您依然可以在 .NET Framework 中使用 FileSystemObject。由於 FileSystemObject 是個「元件物件模型」(COM) 元件,.NET Framework 必須透過 Interop 層級來存取這個物件。 如果要使用元件,.NET Framework 便會為您產生元件的包裝函式。然而,在 .NET Framework 中的 File 類別、FileInfo 類別、DirectoryDirectoryInfo 類別及其他相關類別,都提供使用 FSO 所無法提供的功能,而且不會增加 Interop 層級的額外負荷。

需求

下列清單列出建議使用的硬體、軟體、網路基礎結構及必要的 Service Pack:
  • Visual C++ .NET

示範檔案 I/O 作業

本文的範例說明基本檔案的 I/O 作業。<逐步範例>一節說明如何建立範例程式以示範下列 6 種檔案 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. 啟動 Microsoft Visual Studio .NET 2003。
  2. [檔案] 功能表,指向 [新增],再按一下 [專案]
  3. [專案類型] 下,按一下 [Visual C++ 專案]。在 [範本] 區段,按一下 [Windows Forms Application (.NET)]
  4. [名稱] 方塊中,輸入 Q307398,在 [位置] 方塊中,輸入 C:\,然後按一下 [確定]
  5. 從設計檢視中,開啟 Form1 表單,再按下 F4 以開啟 [屬性] 視窗。
  6. 在 [屬性] 視窗中,展開 [Size] 資料夾。在 [Width] 方塊中,輸入 700。在 [Height] 方塊中,輸入 320
  7. 在 Form1 加入 1 個 ListBox 控制項和 6 個 Button 控制項。

    注意 如果要檢視工具箱,請在 [檢視] 功能表按一下 [工具箱]
  8. 在 [屬性] 視窗中,如下列所示變更 LocationNameSizeTabIndexText 控制項的屬性:
    摺疊此表格展開此表格
    控制項 IDLocationNameSizeTabIndexText
    button1500, 32button1112, 231讀取文字檔
    button2500, 64button2112, 232寫入文字檔
    button3500, 96button3112, 233檢視檔案資訊 
    button4500, 128button4112, 234列出磁碟機
    button5500, 160button5112, 235列出子資料夾
    button6500, 192button6112, 236列出檔案
    listBox124, 24listBox1450, 2000listBox1
  9. 開啟 Form1.h 檔案。在 Form1 類別宣告中,以下列程式碼宣告一個私用的 String 變數:
    private:
    		String *windir;
  10. Form1 類別建構函式中,加入下列程式碼:
    windir = System::Environment::GetEnvironmentVariable("windir");
  11. 如果要執行檔案輸入作業,請加入 System.IO 命名空間。
  12. 按下 SHIFT+F7 以便在設計檢視中開啟 Form1。按兩下 [讀取文字檔],然後貼上下列程式碼:
    // How to read a text file:
    // Use try...catch to deal with a 0 byte file or a non-existant file.
    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(FileNotFoundException *ex)
    {
    	listBox1->Items->Add(ex);
    }  
            
    catch (System::Exception *e)
    { 
    	listBox1->Items->Add(e);
    }
  13. 在 Form1 設計檢視中,按兩下 [寫入文字檔],然後貼上下列程式碼:
    // This demonstrates how to create and to write to a text file.
    StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
    pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
    pwriter->Close();
    listBox1->Items->Clear();
    String *filew = new String(S"File written to C:\\KBTest.txt");
    listBox1->Items->Add(filew);
  14. 在 Form1 設計檢視中,按兩下 [寫入文字檔],按兩下 [檢視檔案資訊],然後將下列程式碼貼入方法中:
    // This code retrieves file properties. The 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()) );
  15. 在 Form1 設計檢視中,按兩下 [檢視檔案資訊],然後貼上下列程式碼:
    // This 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]);
    }
  16. 在 Form1 設計檢視中,按兩下 [列出子資料夾] 按鈕,然後貼上下列程式碼:
    // This code obtains a list of folders. This example uses the 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]);                                                    
    }
  17. 在 Form1 設計檢視中,按兩下 [列出檔案],然後貼上下列程式碼:
    // This code obtains a list of files. This example uses the 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]);
    }
  18. 如果要建立並執行程式,請按下 CTRL+F5。

完整程式碼範例

//Form1.h
#pragma once


namespace Q307398
{
	using namespace System;
	using namespace System::IO;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary> 
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the 
	///          'Resource File Name' property for the managed resource compiler tool 
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>
	public __gc class Form1 : public System::Windows::Forms::Form
	{
	private:
		String *windir;
	public:
		Form1(void)
		{
			windir = System::Environment::GetEnvironmentVariable("windir");
			InitializeComponent();
		}
  
	protected:
		void Dispose(Boolean disposing)
		{
			if (disposing && components)
			{
				components->Dispose();
			}
			__super::Dispose(disposing);
		}
	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;

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container * components;

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			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 = System::Drawing::Point(500, 32);
			this->button1->Name = S"button1";
			this->button1->Size = System::Drawing::Size(112, 23);
			this->button1->TabIndex = 1;
			this->button1->Text = S"Read Text File";
			this->button1->Click += new System::EventHandler(this, button1_Click);
			// 
			// button2
			// 
			this->button2->Location = System::Drawing::Point(500, 64);
			this->button2->Name = S"button2";
			this->button2->Size = System::Drawing::Size(112, 23);
			this->button2->TabIndex = 2;
			this->button2->Text = S"Write Text File";
			this->button2->Click += new System::EventHandler(this, button2_Click);
			// 
			// button3
			// 
			this->button3->Location = System::Drawing::Point(500, 96);
			this->button3->Name = S"button3";
			this->button3->Size = System::Drawing::Size(112, 23);
			this->button3->TabIndex = 3;
			this->button3->Text = S"View File Information";
			this->button3->Click += new System::EventHandler(this, button3_Click);
			// 
			// button4
			// 
			this->button4->Location = System::Drawing::Point(500, 128);
			this->button4->Name = S"button4";
			this->button4->Size = System::Drawing::Size(112, 23);
			this->button4->TabIndex = 4;
			this->button4->Text = S"List Drives";
			this->button4->Click += new System::EventHandler(this, button4_Click);
			// 
			// button5
			// 
			this->button5->Location = System::Drawing::Point(500, 160);
			this->button5->Name = S"button5";
			this->button5->Size = System::Drawing::Size(112, 23);
			this->button5->TabIndex = 5;
			this->button5->Text = S"List Subfolders";
			this->button5->Click += new System::EventHandler(this, button5_Click);
			// 
			// button6
			// 
			this->button6->Location = System::Drawing::Point(500, 188);
			this->button6->Name = S"button6";
			this->button6->Size = System::Drawing::Size(112, 23);
			this->button6->TabIndex = 6;
			this->button6->Text = S"List Files";
			this->button6->Click += new System::EventHandler(this, button6_Click);
			// 
			// listBox1
			// 
			this->listBox1->Location = System::Drawing::Point(24, 24);
			this->listBox1->Name = S"listBox1";
			this->listBox1->Size = System::Drawing::Size(450, 199);
			this->listBox1->TabIndex = 0;
			// 
			// Form1
			// 
			this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
			this->ClientSize = System::Drawing::Size(692, 293);
			this->Controls->Add(this->listBox1);
			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->Name = S"Form1";
			this->Text = S"Form1";
			this->ResumeLayout(false);

		}		private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
			 {// This code shows how to read a text file.
// The try...catch code is to deal with a 0 byte file or a non-existant file.
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(FileNotFoundException *ex)
				{
					listBox1->Items->Add(ex);
				}	     
				        
				catch (System::Exception *e)
				{ 
					listBox1->Items->Add(e);
				}
			 }

private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
		 {// This code demonstrates how to create and to write to a text file.
StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
pwriter->Close();
listBox1->Items->Clear();
String *filew = new String(S"The file was written to C:\\KBTest.txt");
listBox1->Items->Add(filew);
		 }

private: System::Void button3_Click(System::Object *  sender, System::EventArgs *  e)
		 {// This code retrieves file properties. This 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()) );
		 }

private: System::Void button4_Click(System::Object *  sender, System::EventArgs *  e)
		 {// The code 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]);
}
		 }

private: System::Void button5_Click(System::Object *  sender, System::EventArgs *  e)
		 {// This code obtains a list of folders. This example uses the 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]);                                                    
}
		 }

private: System::Void button6_Click(System::Object *  sender, System::EventArgs *  e)
		 {// This code obtains a list of files. This example uses the 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]);
}
		 }

};
}

//Form1.cpp
#include "stdafx.h"
#include "Form1.h"
#include <windows.h>

using namespace My;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
	Application::Run(new Form1());
	return 0;
}

?考

如需詳細資訊,請造訪下列 Microsoft 網站:
http://support.microsoft.com/default.aspx?xmlid=fh%3BEN-US%3Bvcnet
如需有關 Visual C++ .NET 的詳細資訊,請造訪下列 Microsoft Usenet 新聞群組:
Microsoft.public.dotnet.languages.vc
如需有關如何在 Managed Extensions for C++ 中建立 Windows 表單的詳細資訊,請參閱 Visual Studio .NET 說明中的 ManagedCWinFormWiz 範例。

屬性

文章編號: 307398 - 上次校閱: 2004年9月20日 - 版次: 1.0
這篇文章中的資訊適用於:
  • Microsoft Visual C++ .NET 2003 Standard Edition
關鍵字:?
kbhowto kbhowtomaster kbwindowsforms kbio kbnewsgrouplink kbforms kbfileio KB307398
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com