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

.net 为什么这个简单的MemoryStream.Write()实验失败了?,.net,memorystream,.net,Memorystream,我被一个基于字节数组的可写System.IO.MemoryStream的基本实验弄糊涂了,这个字节数组给出了一个异常 数组newBytes用文本初始化 使用数组初始化内存流ms,并将可写标志设置为True 内存流在位置1用一个字节写入 VB.net Try Dim newBytes() As Byte = {0, 128, 255, 128, 0} Dim ms As New System.IO.MemoryStream(newBytes, True) ms.Write

我被一个基于字节数组的可写
System.IO.MemoryStream
的基本实验弄糊涂了,这个字节数组给出了一个异常

  • 数组
    newBytes
    用文本初始化
  • 使用数组初始化内存流
    ms
    ,并将可写标志设置为
    True
  • 内存流在位置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

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


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

    内存流.Write方法有三个参数:

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

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

    正确,如果要确定开始写入的位置,需要使用MemoryStream Seek方法。@oberdannes Position属性是可写的,因此
    ms.Position=0
    也可以工作。这是正确的答案,在我对MSDN页面的理解中有一个令人恼火的微妙缺陷。。!现在我将开始询问有关更改SoundPlayer.Stream.Write()方法的问题,但在此之前,您是否知道可以让我省去这个问题?基本上,我希望在声音缓冲区播放时写入它。我不熟悉
    SoundPlayer
    类,因此可能不熟悉。
    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