Converting Request.InputStream to a string - Part 1

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
*/
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;
}

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment