为什么这个简单的MemoryStream.Write()实验失败了?

时间:2018-10-04 19:40:46

标签: .net memorystream

一个基础实验使我感到困惑,该实验使用基于提供ArgumentException的字节数组的可写System.IO.MemoryStream

  1. 数组newBytes用文字初始化
  2. 使用数组初始化内存流ms,并将可写标志设置为True
  3. 内存流在位置1写入一个字节

VB.net

Try
    Dim newBytes() As Byte = {0, 128, 255, 128, 0}
    Dim ms As New System.IO.MemoryStream(newBytes, True)
    ms.Write({CByte(4)}, 1, 1)
Catch ex as Exception
End Try

C#.net

try
    byte() newBytes = {0, 128, 255, 128, 0};
    System.IO.MemoryStream ms = new System.IO.MemoryStream(newBytes, true);
    ms.Write(byte(4), 1, 1);
catch Exception ex
end try

异常为ArgumentException,其文本为“偏移量和长度超出数组的界限,或者计数大于从索引到源集合结尾的元素数。”

显然,内存流具有Length: 5,并且在位置1写入一个字节应该是完全可行的,为什么会有异常?

1 个答案:

答案 0 :(得分:2)

MemoryStream.Write方法具有三个参数:

  • buffer-从中写入数据的缓冲区
  • offset-缓冲区中从零开始的字节偏移,从此处开始将字节复制到当前流中
  • count-要写入的最大字节数

请注意,第二个参数是输入数组中的偏移量,而不是输出数组中的偏移量。 MemoryStream.Position属性确定输出中的当前偏移量。

相关问题