Is it possible to read from a url into a System.IO.Stream object?
Question
I am attempting to read from a url into a System.IO.Stream object. I tried to use
Dim stream as Stream = New FileStream(msgURL, FileMode.Open)
but I get an error that URI formats are not supported with FileStream objects. Is there some method I can use that inherits from System.IO.Stream that is able to read from a URL?
Solution
VB.Net:
Dim req As WebRequest = HttpWebRequest.Create("url here")
Using stream As Stream = req.GetResponse().GetResponseStream()
End Using
C#:
var req = System.Net.WebRequest.Create("url here");
using (Stream stream = req.GetResponse().GetResponseStream())
{
}
OTHER TIPS
Use WebClient.OpenRead
:
Using wc As New WebClient()
Using stream As Stream = wc.OpenRead(msgURL)
...
End Using
End Using
Yes, you can use a HttpWebRequest object to get a response stream:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
// read the stream
receiveStream.Close();
response.Close();
(Stripped down and simplifed from the docs).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow