【问题标题】:Strange behavior with BinaryWriter and MemoryStream in C#C# 中 BinaryWriter 和 MemoryStream 的奇怪行为
【发布时间】:2013-07-10 00:33:49
【问题描述】:

我有一个具有以下方法的类:

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);
}

在上面的代码中,我知道至少有一个被写入流的值是非零的。结果流在转换为字节数组时包含全零。

我是否错误地使用了流和读取器对象?

【问题讨论】:

  • 你是在使用MemoryStream.ToArray方法转换成数组吗?您是在 Try...Catch 块内调用它吗?是否抛出任何异常?
  • 没有try/catch,我正在使用扩展方法转换为字节数组。已包含上述问题中的方法。

标签: c# .net memorystream binarywriter


【解决方案1】:

您的ToBytes 方法从流的当前位置读取字节到流的末尾。如果流已经位于末尾,则读取零字节。 ToBinary 方法返回的流位于末尾。

看看MemoryStream.ToArray Method

MemoryStream.ToArray 方法

将流内容写入字节数组,而不考虑 Position 属性。

【讨论】:

  • 谢谢。照顾除了这里以外的所有地方的溪流位置。我正在使用基础 Stream 类,因为该方法将通过 MS 以及 FileStream 对象从多个位置调用。
  • 请注意stream.Read(buffer, offset, count); 不一定读取count 很多字节。它读取最多 count 多个字节。看看stackoverflow.com/a/221941
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多