バイト単位で読込したい、書き込みしたい、ファイルを作成したい場合は、FileStreamクラスを使うと実現できます。
尚、Fileクラスで一気にByte配列として読み込むメソッドがありますので、リードの場合は File.ReadAllBytes が便利かもしれませんね。
以下に、FileStream クラスを使った C#, Visual Basic のサンプルコードと実行例を記します。
以下のサンプルコードは以下の動作になります。
using System; using System.IO; class Program { static void Main(string[] args) { string desktopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string filename = System.IO.Path.Combine(desktopPath, "test.dat"); try { // File Open(or Create) and Append mode using (var fs = File.Open(filename, FileMode.Append, FileAccess.Write)) { for (int i = 1; i <= 10; i++) fs.WriteByte((byte)i); } // File Read and stdout using (var fs = File.Open(filename, FileMode.Open, FileAccess.Read)) { long i = 0L; while (i < fs.Length) { Console.WriteLine("{0}: {1}", i, fs.ReadByte()); i += 1; } } } catch (Exception ex) { Console.Error.WriteLine("Exception: " + ex.ToString()); } } }
Imports System Imports System.IO Module Program Sub Main(args As String()) Dim desktopPath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) Dim filename As String = System.IO.Path.Combine(desktopPath, "test.dat") Try 'File Open(or Create) and Append mode Using fs = File.Open(filename, FileMode.Append, FileAccess.Write) For i As Integer = 1 To 10 fs.WriteByte(CByte(i)) Next End Using 'File Read and stdout Using fs = File.Open(filename, FileMode.Open, FileAccess.Read) Dim i As Long = 0L While i < fs.Length Console.WriteLine("{0}: {1}", i, fs.ReadByte) i += 1 End While End Using Catch ex As Exception Console.Error.WriteLine("Exception: " & ex.ToString) End Try End Sub End Module
上記サンプルコードを2回起動しています。
2回目で追記されていることが確認できます。
また、ファイル内容を PowerShellの Format-Hex コマンドレットを使って16進数表示した結果です。
以上、Fileクラスの ReadByte, WriteByte を使ってバイト値のバイナリーファイルの読み書きでした。