[この記事は18年前に書かれました]
バイナリファイルの書き込みには、FileStream、BinaryWriterクラスを使用します。 コンストラクタの引数は、ファイルパス、作成モード、読み取り/書き込みアクセス許可です。
using System.IO;
...
using (FileStream fs = new FileStream(@"C:test.txt", FileMode.Create, FileAccess.Write))
using (BinaryWriter bw = new BinaryWriter(fs))
{
try
{
bw.Write(wdata);
}
finally
{
if (bw != null)
{
bw.Close();
}
if (fs != null)
{
fs.Close();
}
}
}
バイナリファイルの読み込みは同様に、BinaryReaderで行います。
byte[] rdata;
using (FileStream fs = new FileStream(@"C:test.txt", FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
try
{
rdata = new byte[fs.Length];
br.Read(rdata, 0, rdata.Length);
}
finally
{
if (br != null)
{
br.Close();
}
if (fs != null)
{
fs.Close();
}
}
}
上記コードでは行っていませんが、必要に応じてArgumentExceptionやIOException等の例外を処理する必要があります。 また、サイズの大きいデータ処理でパフォーマンスが懸念される場合は、BufferedStreamを使用すると良いでしょう。
・関連記事
テキストファイルの書き込み/読み込み
コメント