#author("2020-05-09T14:59:23+09:00","","")
#navi(../)
* バイナリファイルをバイト配列にすべてを読み込む [#f7d99a82]
バイナリファイルをバイト配列にすべてを読み込むメソッド ''File.ReadAllBytes'' の C#, Visual Basic のサンプルコードと実行結果を紹介します。~
電文ファイルなど、バイト配列に展開し操作したい場合など便利かもしれません。

#contents


* 関連サイト [#p35daca7]
-[[Microsoft .NET | File.ReadAllBytes(String) メソッド>https://docs.microsoft.com/ja-jp/dotnet/api/system.io.file.readallbytes]]
-[[Microsoft .NET | File.WriteAllBytes(String, Byte[]) メソッド>https://docs.microsoft.com/ja-jp/dotnet/api/system.io.file.writeallbytes]]

#htmlinsert(windev-top.html)

* 関連記事 [#o2425495]
-[[バイナリーファイルの作成・リード・ライト(バイト単位の読み書き)>.NET/バイナリーファイルの作成・リード・ライト]]

* 動作確認環境 [#kcddeddc]
-Windows 10 ver.1909
-Visual Studio 2019
-.NET Core
-コンソールアプリケーション 

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

** C# [#acaf2e56]
#ref(Program.cs)
 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 [#e6236899]
#ref(Program.vb)
 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


** 実行結果 [#pefccbc5]
上記のサンプルコードを実行した時のキャプチャになります。
#ref(run.png)

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

#htmlinsert(windev-btm.html)



トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS