C# C中二进制编写器和MemoryStream的奇怪行为#
我有一个使用以下方法的类:C# C中二进制编写器和MemoryStream的奇怪行为#,c#,.net,memorystream,binarywriter,C#,.net,Memorystream,Binarywriter,我有一个使用以下方法的类: public System.IO.Stream ToBinary () { int length = 4144; System.IO.Stream stream = null; System.IO.BinaryWriter writer = null; stream = new System.IO.MemoryStream(length); writer = new System.IO.BinaryWriter(stream)
public System.IO.Stream ToBinary ()
{
int length = 4144;
System.IO.Stream stream = null;
System.IO.BinaryWriter writer = null;
stream = new System.IO.MemoryStream(length);
writer = new System.IO.BinaryWriter(stream);
writer.Write(length);
writer.Write(this._Width);
writer.Write(this._Height);
writer.Write(this._Stride);
writer.Write(this._Bounds.X);
writer.Write(this._Bounds.Y);
writer.Write(this._Bounds.Width);
writer.Write(this._Bounds.Height);
writer.Write(this._A.Length);
for (int i = 0; i < this._A.Length; i++) writer.Write(this._A [i]);
writer.Write(this._R.Length);
for (int i = 0; i < this._R.Length; i++) writer.Write(this._R [i]);
writer.Write(this._G.Length);
for (int i = 0; i < this._G.Length; i++) writer.Write(this._G [i]);
writer.Write(this._B.Length);
for (int i = 0; i < this._B.Length; i++) writer.Write(this._B [i]);
writer.Flush();
return (stream); // If I write the contents of stream to a byte array, each element is 0.
}
public static byte [] ToBytes (this System.IO.Stream stream)
{
return (stream.ToBytes(0, (int) stream.Length));
}
public static byte [] ToBytes (this System.IO.Stream stream, int offset, int count)
{
byte [] buffer = null;
buffer = new byte [count];
stream.Read(buffer, offset, count);
return (buffer);
}
public System.IO.Stream to二进制()
{
整数长度=4144;
System.IO.Stream=null;
System.IO.BinaryWriter writer=null;
流=新系统IO内存流(长度);
writer=newsystem.IO.BinaryWriter(流);
作者:写(长度);
writer.Write(这个宽度);
作者:写(这个高度);
作者:写(这个);
writer.Write(this._.X);
writer.Write(this._.Y);
writer.Write(这个宽度);
书写者。书写(此高度);
作者:写(这个长度);
对于(inti=0;i
在上面的代码中,我知道至少有一个写入流的值是非零的。转换为字节数组时生成的流包含所有零
我是否错误地使用了流和读卡器对象?您的
ToBytes
方法从流的当前位置到流的末尾读取字节。如果流已经位于末尾,则它读取零字节。
ToBinary
方法返回的流位于末尾
请看一下:
MemoryStream.ToArray方法
将流内容写入字节数组,而不考虑Position属性
您的
ToBytes
方法读取从流的当前位置到流末尾的字节。如果流已经位于末尾,则它读取零字节。
ToBinary
方法返回的流位于末尾
请看一下:
MemoryStream.ToArray方法
将流内容写入字节数组,而不考虑Position属性
您是否使用
MemoryStream.ToArray
方法转换为数组?您是否在Try…Catch
块中调用此函数,是否引发了任何异常?没有Try/Catch,我正在使用扩展方法转换为字节数组。您是否使用MemoryStream.ToArray
方法转换为数组?您是否在Try…Catch
块中调用此函数,是否引发了任何异常?没有Try/Catch,我正在使用扩展方法转换为字节数组。已将方法包括在上述问题中。谢谢。除此之外,所有地方都注意到了水流的位置。我使用的是基流类,因为这个方法将在多个地方用MS和FileStream对象调用代码>不一定读取计数
许多字节。它最多可读取count
多个字节。看一看谢谢。除此之外,所有地方都注意到了水流的位置。我使用的是基流类,因为这个方法将在多个地方用MS和FileStream对象调用代码>不一定读取计数
许多字节。它最多可读取count
多个字节。看看