流到字符串

时间:2015-04-26 07:54:17

标签: c# string stream

如何将Stream输出附加到字符串而不是此代码中的文件?

HttpWebResponse res = (HttpWebResponse)httpRequest.GetResponse();

using (Stream output = File.OpenWrite(@"c:\temp\tmp.html"))                   
using (Stream input = res.GetResponseStream())
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
    input.Close();
    output.Close();
}  

2 个答案:

答案 0 :(得分:1)

您可以使用StreamReader

HttpWebResponse res = (HttpWebResponse)httpRequest.GetResponse();

using (Stream input = res.GetResponseStream())
using (var streamReader = new StreamReader(input))
{
    string result = streamReader.ReadToEnd();
} 

请注意,这会将整个string读入内存。

答案 1 :(得分:0)

使用encoding获取字符串,然后使用StringReader读取缓冲区。

            HttpWebResponse res = (HttpWebResponse)httpRequest.GetResponse();

            using (Stream output = File.OpenWrite(@"c:\temp\tmp.html"))
            using (Stream input = res.GetResponseStream())
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, bytesRead);
                }
                input.Close();
                output.Close();

                string sBuffer = Encoding.UTF8.GetString(buffer);
                StringReader reader = new StringReader(sBuffer);
​