Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading