Search code examples
.netmemorystream

Why is this simple MemoryStream.Write() experiment failing?


I am flummoxed by a basic experiment using a writable System.IO.MemoryStream based on a byte array giving an ArgumentException

  1. The array newBytes is initialised with a literal
  2. The memory stream ms is initialised with the array and the writable flag set to True
  3. The memory stream is written with one byte at position 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

The Exception is an ArgumentException with text "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."

Evidently the memory stream has Length: 5 and writing one byte at position 1 should be perfectly doable, why is there an exception?


Solution

  • The MemoryStream.Write method has three parameters:

    • buffer - The buffer to write data from
    • offset - The zero-based byte offset in buffer at which to begin copying bytes to the current stream
    • count - The maximum number of bytes to write

    Note that the second parameter is the offset in the input array, not the offset in the output array. The MemoryStream.Position property determines the current offset in the output.