System.IO.BinaryWriter和 System.IO.BinaryReader 類別用於寫入和讀取字元字串以外的數據。 下列範例示範如何建立空的檔案數據流、將數據寫入其中,以及從中讀取數據。
此範例會在當前目錄中建立名為 Test.data 的 數據檔、建立相關聯的 BinaryWriter 和 BinaryReader 物件,並使用 BinaryWriter 物件將整數 0 到 10 寫入 Test.data,這會將檔案指標保留在檔案結尾。 然後,物件 BinaryReader 會將檔案指標設定回原點,並讀出指定的內容。
備註
如果 Test.data 已存在於目前目錄中, IOException 則會擲回例外狀況。 使用檔案模式選項 FileMode.Create ,而不是 FileMode.CreateNew 一律建立新的檔案,而不擲回例外狀況。
範例
using System;
using System.IO;
class MyStream
{
private const string FILE_NAME = "Test.data";
public static void Main()
{
if (File.Exists(FILE_NAME))
{
Console.WriteLine($"{FILE_NAME} already exists!");
return;
}
using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
for (int i = 0; i < 11; i++)
{
w.Write(i);
}
}
}
using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs))
{
for (int i = 0; i < 11; i++)
{
Console.WriteLine(r.ReadInt32());
}
}
}
}
}
// The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
// It then writes the contents of Test.data to the console with each integer on a separate line.
Imports System.IO
Class MyStream
Private Const FILE_NAME As String = "Test.data"
Public Shared Sub Main()
If File.Exists(FILE_NAME) Then
Console.WriteLine($"{FILE_NAME} already exists!")
Return
End If
Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
Using w As New BinaryWriter(fs)
For i As Integer = 0 To 10
w.Write(i)
Next
End Using
End Using
Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
Using r As New BinaryReader(fs)
For i As Integer = 0 To 10
Console.WriteLine(r.ReadInt32())
Next
End Using
End Using
End Sub
End Class
' The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
' It then writes the contents of Test.data to the console with each integer on a separate line.