檔案處理和 I/O (C++/CLI)

示範使用 .NET Framework 的各種檔案作業。

下列主題示範如何使用 命名空間中 System.IO 定義的類別來執行各種檔案作業。

列舉目錄中的檔案

下列程式碼範例示範如何擷取目錄中的檔案清單。 此外,會列舉子目錄。 下列程式碼範例會使用 GetFilesGetFilesGetDirectories 方法來顯示 C:\Windows 目錄的內容。

範例

// enum_files.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   String^ folder = "C:\\";
   array<String^>^ dir = Directory::GetDirectories( folder );
   Console::WriteLine("--== Directories inside '{0}' ==--", folder);
   for (int i=0; i<dir->Length; i++)
      Console::WriteLine(dir[i]);

   array<String^>^ file = Directory::GetFiles( folder );
   Console::WriteLine("--== Files inside '{0}' ==--", folder);
   for (int i=0; i<file->Length; i++)
      Console::WriteLine(file[i]);

   return 0;
}

監視檔案系統變更

下列程式碼範例會使用 FileSystemWatcher 來註冊對應至所建立、變更、刪除或重新命名之檔案的事件。 當偵測到變更時,您可以使用 FileSystemWatcher 類別來引發事件,而不是定期輪詢目錄以取得檔案的變更。

範例

// monitor_fs.cpp
// compile with: /clr
#using <system.dll>

using namespace System;
using namespace System::IO;

ref class FSEventHandler
{
public:
    void OnChanged (Object^ source, FileSystemEventArgs^ e)
    {
        Console::WriteLine("File: {0} {1}",
               e->FullPath, e->ChangeType);
    }
    void OnRenamed(Object^ source, RenamedEventArgs^ e)
    {
        Console::WriteLine("File: {0} renamed to {1}",
                e->OldFullPath, e->FullPath);
    }
};

int main()
{
   array<String^>^ args = Environment::GetCommandLineArgs();

   if(args->Length < 2)
   {
      Console::WriteLine("Usage: Watcher.exe <directory>");
      return -1;
   }

   FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
   fsWatcher->Path = args[1];
   fsWatcher->NotifyFilter = static_cast<NotifyFilters>
              (NotifyFilters::FileName |
               NotifyFilters::Attributes |
               NotifyFilters::LastAccess |
               NotifyFilters::LastWrite |
               NotifyFilters::Security |
               NotifyFilters::Size );

    FSEventHandler^ handler = gcnew FSEventHandler();
    fsWatcher->Changed += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Created += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Deleted += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Renamed += gcnew RenamedEventHandler(
            handler, &FSEventHandler::OnRenamed);

    fsWatcher->EnableRaisingEvents = true;

    Console::WriteLine("Press Enter to quit the sample.");
    Console::ReadLine( );
}

讀取二進位檔案

下列程式碼範例示範如何使用 命名空間中的 System.IO 兩個類別,從 檔案讀取二進位資料: FileStreamBinaryReaderFileStream 表示實際檔案。 BinaryReader 提供允許二進位存取之資料流程的介面。

程式碼範例會讀取名為 data.bin 的檔案,並包含二進位格式的整數。 如需這類檔案的相關資訊,請參閱 如何:寫入二進位檔案 (C++/CLI)

範例

// binary_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "data.bin";
   try
   {
      FileStream^ fs = gcnew FileStream(fileName, FileMode::Open);
      BinaryReader^ br = gcnew BinaryReader(fs);

      Console::WriteLine("contents of {0}:", fileName);
      while (br->BaseStream->Position < br->BaseStream->Length)
         Console::WriteLine(br->ReadInt32().ToString());

      fs->Close( );
   }
   catch (Exception^ e)
   {
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("File '{0}' not found", fileName);
      else
         Console::WriteLine("Exception: ({0})", e);
      return -1;
   }
   return 0;
}

讀取文字檔

下列程式碼範例示範如何使用 命名空間中 System.IO 定義的 類別,一次 StreamReader 一行開啟和讀取文字檔。 這個類別的實例可用來開啟文字檔,然後使用 System.IO.StreamReader.ReadLine 方法擷取每一行。

此程式碼範例會讀取名為 textfile.txt 且包含文字的檔案。 如需這類檔案的相關資訊,請參閱 如何:寫入文字檔(C++/CLI)。

範例

// text_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";
   try
   {
      Console::WriteLine("trying to open file {0}...", fileName);
      StreamReader^ din = File::OpenText(fileName);

      String^ str;
      int count = 0;
      while ((str = din->ReadLine()) != nullptr)
      {
         count++;
         Console::WriteLine("line {0}: {1}", count, str );
      }
   }
   catch (Exception^ e)
   {
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("file '{0}' not found", fileName);
      else
         Console::WriteLine("problem reading file '{0}'", fileName);
   }

   return 0;
}

擷取檔案資訊

下列程式碼範例示範 類別 FileInfo 。 當您擁有檔案的名稱時,可以使用這個類別來擷取檔案的相關資訊,例如檔案大小、目錄、完整名稱和建立日期和時間,以及上次修改的時間。

此程式碼會擷取 記事本.exe 的檔案資訊。

範例

// file_info.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   array<String^>^ args = Environment::GetCommandLineArgs();
   if (args->Length < 2)
   {
      Console::WriteLine("\nUSAGE : file_info <filename>\n\n");
      return -1;
   }

   FileInfo^ fi = gcnew FileInfo( args[1] );

   Console::WriteLine("file size: {0}", fi->Length );

   Console::Write("File creation date:  ");
   Console::Write(fi->CreationTime.Month.ToString());
   Console::Write(".{0}", fi->CreationTime.Day.ToString());
   Console::WriteLine(".{0}", fi->CreationTime.Year.ToString());

   Console::Write("Last access date:  ");
   Console::Write(fi->LastAccessTime.Month.ToString());
   Console::Write(".{0}", fi->LastAccessTime.Day.ToString());
   Console::WriteLine(".{0}", fi->LastAccessTime.Year.ToString());

   return 0;
}

寫入二進位檔案

下列程式碼範例示範如何將二進位資料寫入檔案。 會使用 命名空間中的 System.IO 兩個類別: FileStreamBinaryWriterFileStream 表示實際檔案,同時 BinaryWriter 提供允許二進位存取之資料流程的介面。

下列程式碼範例會撰寫一個檔案,其中包含二進位格式的整數。 您可以使用如何:讀取二進位檔案 (C++/CLI) 中的 程式碼來讀取此檔案。

範例

// binary_write.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   array<Int32>^ data = {1, 2, 3, 10000};

   FileStream^ fs = gcnew FileStream("data.bin", FileMode::Create);
   BinaryWriter^ w = gcnew BinaryWriter(fs);

   try
   {
      Console::WriteLine("writing data to file:");
      for (int i=0; i<data->Length; i++)
      {
         Console::WriteLine(data[i]);
         w->Write(data[i]);
      }
   }
   catch (Exception^)
   {
     Console::WriteLine("data could not be written");
     fs->Close();
     return -1;
   }

   fs->Close();
   return 0;
}

寫入文字檔

下列程式碼範例示範如何建立文字檔,並使用 命名空間中 System.IO 定義的 類別將文字寫入其中 StreamWriter 。 建 StreamWriter 構函式會採用要建立的檔案名。 如果檔案存在,則會覆寫它(除非您傳遞 True 作為第二個 StringWriter 建構函式引數)。

接著會使用 WriteWriteLine 函式來提交檔案。

範例

// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";

   StreamWriter^ sw = gcnew StreamWriter(fileName);
   sw->WriteLine("A text file is born!");
   sw->Write("You can use WriteLine");
   sw->WriteLine("...or just Write");
   sw->WriteLine("and do {0} output too.", "formatted");
   sw->WriteLine("You can also send non-text objects:");
   sw->WriteLine(DateTime::Now);
   sw->Close();
   Console::WriteLine("a new file ('{0}') has been written", fileName);

   return 0;
}

另請參閱

以 C++/CLI 進行 .NET 程式設計 (Visual C++)
檔案和資料流 I/O
System.IO 命名空間