Converting Request.InputStream to a string - Part 1

| | Comments (3)
Update: See the comments below for some more succinct ways of expressing this code that have been suggested.

Nowhere could I find a simple, concise way of converting the Request.InputStream from an ASP.net page into a string ready for processing, something which is very useful to do if you're passing a large amount of data (such as a constructed XML submission) via the content of an XMLHTTPRequest. So, the following is an amalgam of the different examples I found that appears to work:

private string RequestInputStreamToString() { StringBuilder sb = new StringBuilder(); int streamLength; int streamRead; Stream s = Request.InputStream; streamLength = Convert.ToInt32(s.Length);

Byte[] streamArray = new Byte[streamLength];

streamRead = s.Read(streamArray, 0, streamLength);

for (int i = 0; i < streamLength; i++)
{
sb.Append(Convert.ToChar(streamArray[i]));
}

return sb.ToString();
}

I'm sure that it could be more elegant and there's room for optimisation, but it works well enough for my purposes.

An implementation of the XML Http Request sender (IE specific) that I use with this is below:


/*
Parameters:

sRPCPageUrl: The URL (including query string if appropriate) of the page to call

Notes:

*/
function SynchronousXMLRPCCall(sRPCPageUrl)
{
return SynchronousXMLRPCCallWithPostData(sRPCPageUrl, '');
}

/*
Parameters:

sRPCPageUrl: The URL (including query string if appropriate) of the page to call
sPostData: Post Data to pass to the server as part of the call

Notes:

called by SynchronousXMLRPCCall

*/
function SynchronousXMLRPCCallWithPostData(sRPCPageUrl, sPostData)
{
oXMLDoc = new ActiveXObject("Microsoft.XMLHTTP");
oXMLDoc.open("GET", sRPCPageUrl, false);
oXMLDoc.send(sPostData);
return oXMLDoc;
}

3 Comments

Andrew Fenster said:

That was helpful. You got me on the right track. In .net 2.0, you can do this:

StreamReader reader = new StreamReader(Request.InputStream);
string encodedString = reader.ReadToEnd();
return HttpUtility.UrlDecode(encodedString);

Paul said:

Here's an easier way

Dim str As New System.IO.StreamReader(Request.InputStream)
Dim sBuf As String = str.ReadToEnd()

cool said:

This is the same one as paul said, but i like it using one line of code :)

Dim encodedString As String = new StreamReader(Request.InputStream).ReadToEnd()

About this Entry

This page contains a single entry by Robert Wray published on March 23, 2007 10:02 AM.

Obtaining the string value of an enumeration name was the previous entry in this blog.

Using MSMQ (Message Queuing) from .net is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.04