DataStream.Length and .Position throw an exception of type 'System.NotSupportedException'

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

By doing this, I get a closed error. I checked a lot of posts, but nothing helps me. Any help on this would be greatly appreciated.

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

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

Please attach 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

+3
source share
1 answer

HttpWebResponse.GetResponseStream, Stream , ; , , HTTP-, .

, , FileStream instance , , , , ( , , ).

HTTP , . , , (, Length, Position, Seek) Stream NotSupportedException.

Stream, MemoryStream Stream MemoryStream CopyTo , :

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

    // Use the memory stream.
}

, .NET 4.0 ( CopyTo Stream ), .

+6

All Articles