code_junkie

How do I put a WebResponse into a memory stream?

Nov 11th, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. MemoryStream memStream;
  2. using (Stream response = request.GetResponseStream()) {
  3. memStream = new MemoryStream();
  4.  
  5. byte[] buffer = new byte[1024];
  6. int byteCount;
  7. do {
  8. byteCount = stream.Read(buffer, 0, buffer.Length);
  9. memStream.Write(buffer, 0, byteCount);
  10. } while (byteCount > 0);
  11. }
  12.  
  13. // If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning.
  14. memStream.Seek(0, SeekOrigin.Begin);
  15.  
  16. // Use memStream as required
  17.  
  18. //Load response stream into XMLReader
  19. objXMLReader = new XmlTextReader(objResponseStream);
  20.  
  21. //Declare XMLDocument
  22. XmlDocument xmldoc = new XmlDocument();
  23. xmldoc.Load(objXMLReader);
  24.  
  25. //Set XMLResponse object returned from XMLReader
  26. XMLResponse = xmldoc;
  27.  
  28. //Close XMLReader
  29. objXMLReader.Close();
  30. }
  31.  
  32. //Close HttpWebResponse
  33. objHttpWebResponse.Close();
  34. }
  35.  
  36. Dim request As WebRequest
  37. Dim response As WebResponse = Nothing
  38. Dim s As Stream = Nothing
  39. Dim fs As FileStream = Nothing
  40. Dim file As MemoryStream = Nothing
  41.  
  42. Dim uri As New Uri(String.Format("http://forums.microsoft.com/forums/ShowPost.aspx?PostID=2992978&SiteID=1"))
  43. request = WebRequest.Create(uri)
  44. request.Timeout = 10000
  45. response = request.GetResponse
  46. s = response.GetResponseStream
  47.  
  48. '2 - Receive file as memorystream
  49. Dim read(256) As Byte
  50. Dim count As Int32 = s.Read(read, 0, read.Length)
  51. File = New MemoryStream
  52. Do While (count > 0)
  53. File.Write(read, 0, count)
  54. count = s.Read(read, 0, read.Length)
  55. Loop
  56. File.Position = 0
  57. 'Close responsestream
  58. s.Close()
  59. response.Close()
  60.  
  61. '3 - Save file
  62. fs = New FileStream("c:test.html", FileMode.CreateNew)
  63. count = file.Read(read, 0, read.Length)
  64. Do While (count > 0)
  65. fs.Write(read, 0, count)
  66. count = file.Read(read, 0, read.Length)
  67. Loop
  68. fs.Close()
  69. File.Close()
Add Comment
Please, Sign In to add comment