陋室铭
永远也不要停下学习的脚步(大道至简至易)

posts - 2169,comments - 570,views - 413万

 

  比如返回数据为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();

        }
复制代码

 

posted on   宏宇  阅读(103)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2018-09-10 vs2017配置文件目录
2016-09-10 《Xenogears》(异度装甲)隐含的原型与密码
2008-09-10 Session.Abandon和Session.Clear有何不同
2007-09-10 七种武器——.NET工程师求职面试必杀技(转)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示