Tag Archives: Stream to MemoryStream error

Stream to MemoryStream to solve Stream.Length error report This stream does not support search operations

1.StreamToMemoryStream

 MemoryStream StreamToMemoryStream(Stream instream)
        {
            MemoryStream outstream = new MemoryStream();
             const  int bufferLen = 4096 ;
             byte [] buffer = new  byte [bufferLen];
             int count = 0 ;
             while ((count = instream.Read(buffer, 0 , bufferLen))> 0 )
            {
                outstream.Write(buffer, 0 , count);
            }
            return outstream;
        }

2.Stream.Length error: this stream does not support search

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (data == "" ? "" : " ? " + Data));
                request.Method = " GET " ;
                 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {                       
                        Stream rs = response.GetResponseStream();                                  
                        
                        var ms = StreamToMemoryStream (rs);
                        ms.Seek( 0 , SeekOrigin.Begin);                         int buffsize =( int ) ms.Length ; //rs.Length This stream does not support searching, first convert to MemoryStream
                         byte [] bytes = new  byte [buffsize];

                        ms.Read(bytes, 0 , buffsize);
                        ms.Flush();ms.Close(); 
              rs.Flush();rs.Close(); 
                }