I am flummoxed by a basic experiment using a writable System.IO.MemoryStream
based on a byte array giving an ArgumentException
newBytes
is initialised with a literalms
is initialised with the array and the writable flag set to True
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?
The MemoryStream.Write
method has three parameters:
buffer
- The buffer to write data fromoffset
- The zero-based byte offset in buffer at which to begin copying bytes to the current streamcount
- The maximum number of bytes to writeNote 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.