从网址转换为流

时间:2010-06-24 02:56:21

标签: c# stream

我试图将Url转换为Stream但我不确定我是对还是错。

protected Stream GetStream(String gazouUrl)
{
    Stream rtn = null;
    HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(gazouUrl);
    HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();

    using (StreamReader sReader = new StreamReader(aResponse.GetResponseStream(), System.Text.Encoding.Default))
    {
        rtn = sReader.BaseStream;
    }
    return rtn;
}

我是在正确的轨道上吗?

3 个答案:

答案 0 :(得分:29)

我最终做了一个较小的版本并使用WebClient代替旧的Http请求代码:

private static Stream GetStreamFromUrl(string url)
{
    byte[] imageData = null;

    using (var wc = new System.Net.WebClient())
        imageData = wc.DownloadData(url);

    return new MemoryStream(imageData);
}

答案 1 :(得分:15)

您无需在那里创建StreamReader。只需return aResponse.GetResponseStream();。该方法的调用者还需要在完成后调用流上的Dispose

答案 2 :(得分:0)

这是我的方法,您可以自行处理错误;-)

    private MemoryStream GetStreamFromUrl(string url)
    {
        byte[] imageData = null;
        MemoryStream ms;

        ms = null;

        try
        {
            using (var wc = new System.Net.WebClient())
            {
                imageData = wc.DownloadData(url);
            }
            ms = new MemoryStream(imageData);
        }
        catch (Exception ex)
        {
            //forbidden, proxy issues, file not found (404) etc
        }

        return ms ;
    }