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

标签 .net memorystream

我对使用基于字节数组的可写 System.IO.MemoryStream 进行基本实验感到困惑,该实验给出了 ArgumentException

  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写入一个字节应该是完全可行的,为什么会有异常(exception)?

最佳答案

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

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

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

关于.net - 为什么这个简单的 MemoryStream.Write() 实验失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52654031/

相关文章:

mysql - 关于具有多对多关系的 3 个表的 SQL 查询帮助

.net - 如何在 PropertyGrid 中为模态 UITypeEditor 重新标记省略号按钮?

c# - 在 C# 中创建包含内存流/字节数组中的文件的压缩文档

xml - 使用 MemoryStream 创建 Open XML 电子表格时出现 Excel 和 "unreadable content"

c# - MemoryStream CopyTo 仅部分写入

c# - 使用 C# 的 odp.net 批量复制

.net - 在 .NET 2.0+ 中针对 PayPal API 进行编码的示例?

.net - 如何将分层数据从 DataTable 转换为 JSON

c# - 如果发送了很多消息,如何写入 MemoryStream

c# - 将excel工作簿转换为内存流/字节数组以下载