views:

377

answers:

3

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?

+3  A: 

VB.Net:

Using req As HttpWebRequest = HttpWebRequest.Create("url here"), _
      stream As Stream = req.GetResponse().GetResponseStream()

End Using

C#:

using (HttpWebRequest req = HttpWebRequest.Create("url here") )
using (Stream stream = req.GetResponse().GetResponseStream() )
{

}
Joel Coehoorn
+7  A: 

Use WebClient.OpenRead :

Dim wc As New WebClient();
Dim stream As Stream = wc.OpenRead(msgURL)
Thomas Levesque
Ah, I didn't know OpenRead existed. I'll remember that one.
B.R.
I didn't know either... I just guessed something like that existed, and checked in MSDN library ;)
Thomas Levesque
Of course the simplest way... Add code to show closing of the stream and disposing of the web client, and it's just perfect. :)
Guffa
A: 

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).

Guffa