4
4

More than 3 years have passed since last update.

バイナリファイル読み書き(C#)

Posted at

概要

C#でバイナリファイルを操作することってそんなにないけどメモ

  • 読み込みにはBinaryReader、書き込みにはBinaryWriterを使う
  • Closeし忘れを防ぐため、usingステートメントを使う

読み込み

ファイルが存在しない場合は"System.IO.FileNotFoundException"がスローされる。

// インスタンス生成
BinaryReader reader = new BinaryReader(File.OpenRead(<ファイル名>));

バイナリファイルの内容をコンソール出力するサンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace BinaryFileReadSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // "BinaryFile1.bin"を開く
            using (BinaryReader reader = new BinaryReader(File.OpenRead("BinaryFile1.bin")))
            {
                int ret;
                byte[] buf = new byte[4];

                // 4byte読み取り
                ret = reader.Read(buf, 0, 4);

                // 1byte以上読み取ったか
                // ※インデックスがファイルの末尾だった場合、Read()は0を返す
                while (ret > 0)
                {
                    // 読み取った内容を16進数としてコンソールに出力
                    for (int i = 0; i < ret; i++)
                    {
                        Console.WriteLine(buf[i].ToString("x"));
                    }

                    ret = reader.Read(buf, 0, 4);
                }
            }
        }
    }
}

書き込み

ファイルが存在しない場合は作成される。

// インスタンス生成
BinaryWriter writer = new BinaryWriter(File.OpenWrite(<ファイル名>)

文字列をファイルに書き込み、その内容をコンソール出力するサンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace BinaryFileWriteSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // "BinaryFile2.bin"を開く
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite("BinaryFile2.bin")))
            {
                byte[] buf = new byte[] { 0x01, 0x02, 0x03, 0x04 };

                // 書き込み
                writer.Write(buf);
            }


            // 書き込んだ内容を読み込んでコンソール出力
            using (BinaryReader reader = new BinaryReader(File.OpenRead("BinaryFile2.bin")))
            {
                int ret;
                byte[] buf = new byte[4];

                ret = reader.Read(buf, 0, 4);

                while (ret > 0)
                {
                    for (int i = 0; i < ret; i++)
                    {
                        Console.WriteLine(buf[i].ToString("x"));
                    }

                    ret = reader.Read(buf, 0, 4);
                }
            }
        }
    }
}

おわりに

良いサンプルってなかなか思いつかない

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4