KWallace
KWallace

Reputation: 1698

C# .NET StreamReader() returning literal length of buffer as a string instead of actual stream data

I'm not even sure how to adequately describe this problem. In reading a stream, the text string I am building in chunks is just the literal length of the buffer, over and over again.

string json = "";

context.Request.InputStream.Position = 0;

using (StreamReader inputStream = new StreamReader(context.Request.InputStream)) {

    while (inputStream.Peek() >= 0) {

        char[] buffer = new char[4096];

        json += inputStream.Read(buffer, 0, buffer.Length);

        System.Console.WriteLine(jsonInput.Length);

    }

}

// json = "40964096409640964096 ... 4096"

Any idea what's wrong here?

Thanks

Upvotes: 0

Views: 347

Answers (1)

PMF
PMF

Reputation: 17185

inputStream.Read(buffer, 0, buffer.Length); returns the number of bytes read from the stream, which is 4096 as long as there's data available. The + operator on string in json += ... does an implicit conversion to string, so what you're summing up in the json variable is really a concatenation of the buffer length. What you want to do is to concatenate the buffer instead, eg with

int dataRead = inputStream.Read(buffer, 0, buffer.Length);
json += Encoding.ASCII.GetString(buffer, 0, dataRead);

Upvotes: 1

Related Questions