.net 是否可以从 url 读取到 System.IO.Stream 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1223311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to read from a url into a System.IO.Stream object?
提问by swolff1978
I am attempting to read from a url into a System.IO.Stream object. I tried to use
我正在尝试从 url 读取到 System.IO.Stream 对象。我试着用
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?
但我收到一个错误,即 FileStream 对象不支持 URI 格式。是否有一些我可以使用继承自 System.IO.Stream 的方法可以从 URL 中读取?
回答by Thomas Levesque
Use WebClient.OpenRead:
使用WebClient.OpenRead:
Using wc As New WebClient()
Using stream As Stream = wc.OpenRead(msgURL)
...
End Using
End Using
回答by Joel Coehoorn
VB.Net:
VB.Net:
Dim req As WebRequest = HttpWebRequest.Create("url here")
Using stream As Stream = req.GetResponse().GetResponseStream()
End Using
C#:
C#:
var req = System.Net.WebRequest.Create("url here");
using (Stream stream = req.GetResponse().GetResponseStream())
{
}
回答by Guffa
Yes, you can use a HttpWebRequest object to get a response stream:
是的,您可以使用 HttpWebRequest 对象来获取响应流:
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).
(从文档中剥离和简化)。

