如何将锯齿状数组字节[][]保存到文件中



我正在尝试下载字节数组列表,但类型为byte[][],这在尝试创建文件时会导致问题,因为它需要byte[]

byte[][] imgdata = image.ImageByteArrayList;
using (FileStream file = new FileStream(FileNameLocation, FileMode.Create, System.IO.FileAccess.Write))
{
file.Write(imgdata, 0, imgdata.Length); //error here
file.Flush();
file.Close();
file.Dispose();
}

有没有办法将byte[][]转换为byte[]?或者还有其他下载方式吗?

JaggedArrayHelper类,用于保存和加载字节[][]的锯齿状数组

static public class JaggedArrayHelper
{
static public void Save(string filename, byte[][] array)
{
using ( var file = new FileStream(filename, FileMode.Create, FileAccess.Write) )
{
foreach ( var row in array )
{
var sizeRow = BitConverter.GetBytes(row.Length);
file.Write(sizeRow, 0, sizeRow.Length);
file.Write(row, 0, row.Length);
}
file.Flush();
file.Close();
}
}
static public byte[][] Load(string filename)
{
var array = new byte[0][];
using ( var file = new FileStream(filename, FileMode.Open, FileAccess.Read) )
{
int countRead;
int countItems;
int sizeInt = sizeof(int);
var sizeRow = new byte[sizeInt];
while ( true )
{
countRead = file.Read(sizeRow, 0, sizeInt);
if ( countRead != sizeInt )
break;
countItems = BitConverter.ToInt32(sizeRow, 0);
var data = new byte[countItems];
countRead = file.Read(data, 0, countItems);
if ( countRead != countItems )
break;
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = data;
}
file.Close();
}
return array;
}
}

测试

static void TestJaggedArray()
{
string filename = "c:\test.bin";
byte[][] data = new byte[4][];
data[0] = new byte[] { 10, 20, 30, 40, 50 };
data[1] = new byte[] { 11, 21, 31, 41, 51, 61, 71, 71, 81, 92 };
data[2] = new byte[] { 12, 22, 32 };
data[3] = new byte[] { 13, 23, 33, 43, 53, 63, 73 };
Action print = () =>
{
foreach ( var row in data )
{
Console.Write("  ");
foreach ( var item in row )
Console.Write(item + " ");
Console.WriteLine();
}
};
Console.WriteLine("Jagged array before save:");
print();
JaggedArrayHelper.Save(filename, data);
data = JaggedArrayHelper.Load(filename);
Console.WriteLine();
Console.WriteLine("Jagged array after load:");
print();
}

输出

Jagged array before save:
10 20 30 40 50
11 21 31 41 51 61 71 71 81 92
12 22 32
13 23 33 43 53 63 73
Jagged array after load:
10 20 30 40 50
11 21 31 41 51 61 71 71 81 92
12 22 32
13 23 33 43 53 63 73

未来改进

我们可以添加一些字段来定义头,以帮助识别文件描述和类型,如JaggedBytesArray

我们还可以管理读取的数据与预期计数不匹配的情况,除了中断循环之外,还可以显示消息或引发异常。

这可以完成您想要的操作,将每一行图像数据依次写入输出文件:

byte[][] imgdata = image.ImageByteArrayList;
using (FileStream file = new FileStream(FileNameLocation, FileMode.Create, System.IO.FileAccess.Write))
{
for (int i = 0;  i < imgdata.Length;  i++)
file.Write(imgdata[i], 0, imgdata[i].Length);   // Write a row of bytes
file.Flush();
file.Close();
file.Dispose();
}

这具有在适当位置使用图像阵列的优点,而不需要将其转换为不同的一维阵列(这可能非常昂贵(。

相关内容

  • 没有找到相关文章