23

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?

Eugene
  • 389
  • 1
  • 7
  • 18
swolff1978
  • 1,845
  • 7
  • 28
  • 44

3 Answers3

36

Use WebClient.OpenRead :

Using wc As New WebClient()
    Using stream As Stream = wc.OpenRead(msgURL)
        ...
    End Using
End Using
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
28

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())
{

}
Fab
  • 14,327
  • 5
  • 49
  • 68
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Using this code I wasn't able to deserialize the content on the other end of the web request. I suggest using Thomas Levesque's answer below, as it worked perfectly. – Nathan C. Tresch Apr 14 '14 at 14:56
2

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
  • 687,336
  • 108
  • 737
  • 1,005