このエントリーをはてなブックマークに追加


バイナリファイルをバイト配列にすべてを読み込む

バイナリファイルをバイト配列にすべてを読み込むメソッド File.ReadAllBytes の C#, Visual Basic のサンプルコードと実行結果を紹介します。
電文ファイルなど、バイト配列に展開し操作したい場合など便利かもしれません。

関連サイト

関連記事

動作確認環境

  • Windows 10 ver.1909
  • Visual Studio 2019
  • .NET Core
  • コンソールアプリケーション

File.readallbytesサンプルコード

本サンプルコードでは、 File.WriteAllBytes メソッドを使ってバイト配列をファイルに書き込み
File.readallbytes メソッドで File.WriteAllBytes メソッドで作成したファイルをすべて読み込み、値を画面に出力します。
作成するファイルは、デスクトップに出力されます。

  1. File.WriteAllBytes でファイルを作成し書き込み。
  2. File.ReadAllBytes で 作成したファイルを読み込み、値を16進数で出力。

C#

using System;

class Program
{
    static void Main(string[] args)
    {
        // Desktop path
        string desktopPath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        // Read and Write filename
        var filename = System.IO.Path.Combine(desktopPath, @"bytes.dat");

        // Output byte data
        byte[] outBytes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

        // Write file
        System.IO.File.WriteAllBytes(filename, outBytes);
        // Read file and hex output
        byte[] inBytes = System.IO.File.ReadAllBytes(filename);
        for (int i = 1; i <= inBytes.Length; i++)
        {
            Console.WriteLine("{0} : {1:X}", i - 1, inBytes.GetValue(i - 1));
        }
    }
}

Visual Basic

Imports System

Module Program
    Sub Main(args As String())

        'Desktop path
        Dim desktopPath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
        'Read and Write filename
        Dim filename = System.IO.Path.Combine(desktopPath, "bytes.dat")

        'Output byte data
        Dim outBytes As Byte() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

        'Write file
        System.IO.File.WriteAllBytes(filename, outBytes)
        'Read file and hex output
        Dim inBytes As Byte() = System.IO.File.ReadAllBytes(filename)
        For i As Integer = 1 To inBytes.Length
            Console.WriteLine("{0} : {1:X}", i - 1, inBytes.GetValue(i - 1))
        Next

    End Sub
End Module

実行結果

上記のサンプルコードを実行した時のキャプチャになります。

run.png

以上、バイナリファイルをバイト配列にすべてを読み込む File.ReadAllBytes メソッドを利用したサンプルコードの紹介でした。


添付ファイル: fileProgram.vb 177件 [詳細] fileProgram.cs 169件 [詳細] filerun.png 181件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2020-05-09 (土) 15:00:00