httpwebrequest抓取网页数据非字符串时要使用流直接写文件

  比如返回数据为Excel,图片等等非字符串数据。不要使用reader.ReadToEnd();字符串格式的才使用这个。
  直接存Stream为cvs或者xls。

    public static Stream HttpPost2(string url)
    {
        HttpWebResponse response = HttpPost(url);

        //将获取的网络流转化成内存流
        Stream stream = response.GetResponseStream();

        MemoryStream memoryStream = new MemoryStream();

        //将基础流写入内存流
        const int bufferLength = 1024;
        byte[] buffer = new byte[bufferLength];
        int actual = stream.Read(buffer, 0, bufferLength);
        while (actual > 0)
        {
            // 读、写过程中,流的位置会自动走。
            memoryStream.Write(buffer, 0, actual);
            actual = stream.Read(buffer, 0, bufferLength);
        }
        memoryStream.Position = 0;

        return memoryStream;

    }
        private static void WriteThis2(string filePath, string fileName, Stream stream)
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            //把Stream转换成 byte[]
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            //设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            //把byte[]写入文件
            string path = Path.Combine(filePath, fileName);
            FileStream fs = new FileStream(path, FileMode.Create);

            BinaryWriter bw = new BinaryWriter(fs);
            //开始写入
            bw.Write(bytes);
            //清空缓冲区、关闭流
            bw.Flush();
            bw.Close();
            fs.Close();

        }
原文地址:https://www.cnblogs.com/cuihongyu3503319/p/15250605.html