0

I am using a web service that returns xml an I want to read it into a string. I am using ReadToEnd method of StreamReader class but at this moment OutOfMemory Exception occurs because of the large amount of xml data. Is there any way to get this .My code is below

        Stream dataStream;
        WebResponse response;
        string responseFromServer = string.Empty;
        string url = myurl;

        WebRequest request = WebRequest.Create(url);

        ASCIIEncoding encoding = new ASCIIEncoding();

        byte[] data = encoding.GetBytes(postData.ToString());

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        dataStream = request.GetRequestStream();
        dataStream.Write(data, 0, data.Length);
        dataStream.Close();
        response = request.GetResponse();

       using (Stream stream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                try
                {
                    responseFromServer = reader.ReadToEnd();
                }
                catch (Exception ex)
                {
                  throw ex;         
                }             
            }
        }
  • 2
    Do not use `ReadToEnd` in a stream, that completely defeats its purpose. You use streams by reading bytes or lines, acting on each once, then discarding it and processing the next byte or line. Oh, and remove `catch(Exception ex) throw ex;` from all code you ever write. – Dour High Arch Dec 09 '13 at 17:17
  • What do you want to do with the data? Do you want to save it to a file? Build an XML document from it? Read and process it in-line? The answer to that question will determine how you read the data from the stream. – Jim Mischel Dec 09 '13 at 17:37
  • I want to load xml document to my XmlDocument object. I used ReadToEnd method to create XMLDocument object. – user2762782 Dec 09 '13 at 17:52
  • Why do you want to “load xml document”? Please [describe your end goal](http://meta.stackexchange.com/q/66377/135230), not what you are doing, because what you are doing won’t work. – Dour High Arch Dec 09 '13 at 18:18
  • My main aim is parsing xml value and use it for other platforms. My parsing algorithm is ready but now I'm not getting the string which loads my XmlDocument object. Last step I want to do is below. If I read correctly this Stream into my responseFromServer string, rest of the work is done. Thanks for helping. XmlDocument doc = new XmlDocument(); doc.LoadXml(responseFromServer); – user2762782 Dec 09 '13 at 18:39

1 Answers1

1

There is a Load overload that takes a TextReader. StreamReader derives from TextReader, so you should be able to write doc.Load(reader).

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351