This will work:
private static Stream ConvertToStream(string fileUrl) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { MemoryStream mem = new MemoryStream(); Stream stream = response.GetResponseStream(); stream.CopyTo(mem,4096); return mem; } finally { response.Close(); } }
However, you are solely responsible for the lifetime of the returned memory stream.
The best approach:
private static void ConvertToStream(string fileUrl, Stream stream) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { Stream response_stream = response.GetResponseStream(); response_stream.CopyTo(stream,4096); } finally { response.Close(); } }
Then you can do something like:
using (MemoryStream mem = new MemoryStream()) { ConvertToStream('http://www.example.com/',mem); mem.Seek(0,SeekOrigin.Begin); ... Do something else ... }
You can also return the response stream directly, but you will need to check its lifetime, having released the answer, it can free the stream, and, therefore, a copy of mem.
Lloyd source share