首页 > 解决方案 > 写入字节数组的大小(C# winforms)

问题描述

我正在将一些内容写入二进制文件。一项是图像,因此将图像转换为字节数组并将其写入如下。

 BinaryWriter bw = (BinaryWriter)writer;
 WritePropertyTag(property); //IMAGE_TAG
 bw.Write((short)(sizeofshort + imagedata.Length + (writesize ? sizeofshort : 0)));
 if (writesize)
 {
     bw.Write((short)(imagedata.Length));
 }
 bw.Write(imagedata);

并用下面的代码读回它:

short datasize = binReaderIn.ReadInt16();
byte[] data = new byte[datasize];
binReaderIn.Read(data, 0, datasize);
Image img = (Bitmap)((new ImageConverter()).ConvertFrom(data));

如果字节数组相对较小(短数字),上述方法非常有效。

当我们想要存储更大的图像(大约字节数组大小为 25k)时,它会失败。我尝试在上面的代码块中使用 long 而不是 short 并使用 ReadInt64() 方法读取,但没有得到正确的大小。请帮忙。谢谢。

标签: c#

解决方案


BinaryWriter bw = (BinaryWriter)writer;
WritePropertyTag(property);
bw.Write((uint)(sizeofshort + data.Length + (writesize ? sizeofshort : 0)));
if (writesize)
{
   bw.Write((uint)(data.Length));
}
bw.Write(data);

使用 uint 而不是 short 解决了这个问题。


推荐阅读