ファイルをbyte配列に読み込むコードを紹介します。
ファイルをbyte配列に読み込む場合は、FileStreamでファイルを開き、FileStreamのRead()メソッドを用います。
下図のUIを作成します。Buttonと複数行のTextBoxを一つづつ配置します。
下記のコードを記述します。主にButton1のClickイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileStreamToByteArray
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
for (int i = 0; i < data.Length; i++) {
textBox_output.Text += string.Format("{0:X2}, ",data[i]);
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
for (int i = 0; i < data.Length; i++) {
textBox_output.Text += string.Format("{0:X2}, ",data[i]);
}
}
}
OpenFileDialogでファイルが選択されると、FileStreamクラスを作成しファイルを開きます。
ファイル内容を読み込むbyte[] dataを宣言します。配列の長さはファイルストリームの長さと同じにします。
FileStreamクラスのRead()メソッドを呼び出しファイルストリームからbyte配列にデータを読み込みます。データの読み込み後FileStreamクラスのClose()メソッドを呼び出し、ストリームを閉じます。
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
今回は下記のテキストファイルを読み込みます。
ABCDE
Penguin
あいうえお
浅間山
バイナリエディタで開いた内容は下記です。
上記のプログラムのプロジェクトを実行します。
下図のウィンドウが表示されます。
[Button1]をクリックしてサンプルファイルを開きます。下図の結果が表示されます。バイナリエディタで開いた際の結果と同じ結果が出力されました。
FileStreamから byte[]配列にデータを読み込む(変換)するには、Read()メソッドを用います。以下の例は、FileStreamのデータをbyte[]配列に読み込む例です。
FileStream fs = new FileStream("c:\memo.txt", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
//data[]が得られるbyte配列