共用方式為


HOW TO:寫入二進位檔案

更新:2007 年 11 月

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

下列程式碼範例會以二進位格式撰寫含有整數的檔案。這個檔案可以使用 HOW TO:讀取二進位檔案中的程式碼讀取。

範例

// 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;
}

請參閱

其他資源

檔案和資料流 I/O

.NET 程式設計指南