从网址转换为流

Hoq*_*que 24 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;
}
Run Code Online (Sandbox Code Playgroud)

我是在正确的轨道上吗?

bal*_*dre 33

我最终做了一个较小的版本,WebClient而是使用旧的Http Request代码:

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

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

    return new MemoryStream(imageData);
}
Run Code Online (Sandbox Code Playgroud)


Qua*_*ter 15

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

  • 请根据答案要求在此处添加代码修复程序. (2认同)

Mau*_*rez 5

当前的答案缺少如何使用的示例GetResponseStream()

这是一个例子

    // Creates an HttpWebRequest with the specified URL.
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    // Sends the HttpWebRequest and waits for the response.         
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    // Gets the stream associated with the response.
    Stream receiveStream = myHttpWebResponse.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    // Pipes the stream to a higher level stream reader with the required encoding format.
    StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
    Char[] read = new Char[256];
    // Reads 256 characters at a time.
    int count = readStream.Read( read, 0, 256 );
    Console.WriteLine("HTML...\r\n");
    while (count > 0)
        {
            // Dumps the 256 characters on a string and displays the string to the console.
            String str = new String(read, 0, count);
            Console.Write(str);
            count = readStream.Read(read, 0, 256);
        }
    Console.WriteLine("");
    // Releases the resources of the response.
    myHttpWebResponse.Close();
    // Releases the resources of the Stream.
    readStream.Close();
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅 - https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.getresponsestream?view=net-5.0