dataStream.Length and .Position threw an exception of type 'System.NotSupportedException'

37,236

When you call HttpWebResponse.GetResponseStream, it returns a Stream implementation that that doesn't have any recall ability; in other words, the bytes that are sent from the HTTP server are sent directly to this stream for consumption.

This is different from say, a FileStream instance in that if you want to read a section of the file that you've already consumed through the stream, the disk head can always be moved back to the location to read the file from (more than likely, it's buffered in memory, but you get the point).

With an HTTP response, you'd have to actually reissue the request to the server in order to get the response again. Because that response is not guaranteed to be the same, most of the position related methods and properties (e.g. Length, Position, Seek) on the Stream implementation passed back to you throw a NotSupportedException.

If you need to move backwards in the Stream, then you should create a MemoryStream instance and copy the response Stream into the MemoryStream through the CopyTo method, like so:

using (var ms = new MemoryStream())
{
    // Copy the response stream to the memory stream.
    webRequest.GetRequestStream().CopyTo(ms);

    // Use the memory stream.
}

Note, if you aren't using .NET 4.0 or later (where CopyTo on the Stream class was introduced) then you can copy the stream manually.

Share:
37,236
NewGirlInCalgary
Author by

NewGirlInCalgary

Updated on May 23, 2020

Comments

  • NewGirlInCalgary
    NewGirlInCalgary almost 4 years

    I am trying to post some data from asp.net to webservice using http post.

    While doing that I am getting the enclosed error. I have checked many post but nothing helps me really. Any help onto this will greatly appreciated.

    Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'

    Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'

    Enclosed please my code:

    public XmlDocument SendRequest(string command, string request)
    {
        XmlDocument result = null;
    
        if (IsInitialized())
        {
            result = new XmlDocument();
    
            HttpWebRequest webRequest = null;
            HttpWebResponse webResponse = null;
    
            try
            {
                string prefix = (m_SecureMode) ? "https://" : "http://";
                string url = string.Concat(prefix, m_Url, command);
    
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "POST";
                webRequest.ContentType = "text/xml";
                webRequest.ServicePoint.Expect100Continue = false;
    
                string UsernameAndPassword = string.Concat(m_Username, ":", m_Password);
                string EncryptedDetails = Convert.ToBase64String(Encoding.ASCII.GetBytes(UsernameAndPassword));
    
                webRequest.Headers.Add("Authorization", "Basic " + EncryptedDetails);
    
                using (StreamWriter sw = new StreamWriter(webRequest.GetRequestStream()))
                {
                    sw.WriteLine(request);
                }
    
                // Assign the response object of 'WebRequest' to a 'WebResponse' variable.
                webResponse = (HttpWebResponse)webRequest.GetResponse();
    
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
                {
                    result.Load(sr.BaseStream);
                    sr.Close();
                }
            }
    
            catch (Exception ex)
            {
                string ErrorXml = string.Format("<error>{0}</error>", ex.ToString());
                result.LoadXml(ErrorXml);
            }
            finally
            {
                if (webRequest != null)
                    webRequest.GetRequestStream().Close();
    
                if (webResponse != null)
                    webResponse.GetResponseStream().Close();
            }
        }
    
        return result;
    }
    

    Thanks in advance !!

    Ratika