singhster
singhster

Reputation: 23

VB.NET InputStream is empty

I'm using .NET 4.0 and am attempting to get the Request.InputStream into a string. I've tried the obvious:

Dim req As HttpRequest = HttpContext.Current.Request
' Log input stream length
util.SystemError("inputstream length = " + req.InputStream.Length.ToString, "MBOL")
req.InputStream.Position = 0
Dim encodedString As String = New StreamReader(req.InputStream).ReadToEnd()

This shows me the inputstream length is 1671, but the encodedString I get is empty. I've added a try / catch around it, but it doesn't seem to error, it just returns an empty string.

Any ideas where this could be going wrong? Thanks in advance for any assistance with this.

Upvotes: 2

Views: 1679

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

An input stream cannot be necessarily be read several times, it’s by contract read-once (though specific implementations may relax this restriction).

As a consequence, you cannot take its length since that actually reads the stream. Even resetting its position to 0 isn’t guaranteed to work (and doesn’t, as you can see).

If you want to get the length of the content before reading it, you need to rely on the Content-Length header field. Note that the server doesn’t have to provide this. The only 100% reliable way of getting the content length is to read the content, then get its length.

It could be argued that the Stream base class shouldn’t have a Length property at all. It’s a weak design.

Upvotes: 1

Related Questions