Search code examples
c#.netvb.netashx

Why Request.InputStream contains extra byte?


I am uploading byte array to ASHX handler

byte[] serializedRequest = SerializeRequest();

var uri = new Uri(_server.ActionUrl);
using (WebClient client = new WebClient())
{
    client.UploadData(uri, serializedRequest);
}

Which is received by handler

Dim str As Stream = context.Request.InputStream
Dim transformation(str.Length - 1) As Byte ' here I have extra "0"-byte
str.Position = 0
str.Read(transformation, 0, transformation.Length)

As you see, I have to do str.Length - 1 to declare byte array. And this is in development. I don't even know how it will behave when deployed. Where does this byte come from? Is this a reliable way or should I add some bytes at the start of the stream to tell how many bytes to read from Request.InputStream?


Solution

  • Dim x(y) as Byte actually means "array with upper bound y (length = y + 1)" (Arrays in VB.NET).

    Dim transformation(str.Length) As Byte actually declares larger array than you need, so str.Length - 1 statement is correct.

    There is really no 0-value byte, because Stream.Read() does not need to read stream to the end (check method return value) and leaves extra byte with default (0) value.