[.NET クラスライブラリ Tips][BinaryReader] バイナリデータを読み込む

スポンサーリンク

本記事の概要

この記事では、BinaryReader クラスを使用して、バイナリデータを読み込む方法について説明します。

公式サイト情報はコチラを参照してください。

バイナリデータを読み込むには?

1.まず、System.IO名前空間をインポートします。

using System.IO;

2.ファイルストリームを作成します。第1引数んは読み込むファイルのパスを、第2引数に FileMode.Open を指定します
※前回の記事「データをバイナリで書き込む」で作成したファイルを読み込んでいます。

FileStream fileStream = new FileStream(@"C:\work\file.bin", FileMode.Open);

3.バイナリリーダーを作成します。

BinaryReader reader = new BinaryReader(fileStream);

4.ファイルから読み取るデータ型を指定します。

int intValue;
double doubleValue;
string stringValue;

5.バイナリリーダーを使用して、ファイルからデータを読み取ります。

intValue = reader.ReadInt32();
doubleValue = reader.ReadDouble();
stringValue = reader.ReadString();

Console.WriteLine(intValue.ToString());
Console.WriteLine(doubleValue.ToString());
Console.WriteLine(stringValue.ToString());

6.最後に、ファイルストリームとバイナリリーダーを閉じます。

reader.Close();
fileStream.Close();
実行例

実行例

 

Please follow and like us:

コメント

タイトルとURLをコピーしました