C# 将 Stream 优雅的保存到文件的方法

C# 将 Stream 优雅的保存到文件的方法

这篇文章主要介绍了C#将 Stream保存到文件的方法,如何优雅将 Stream 保存到文件

1. 最优雅的方法:通过 CopyTo 或 CopyToAsync 的方法

using (var fileStream = File.Create("C:\\lindexi\\File.txt"))
{
    inputStream.Seek(0, SeekOrigin.Begin);//设置复制开始的地方
    iputStream.CopyTo(fileStream);
}

用异步方法会让写入的时间长一点,但是会让总体性能更好,让 CPU 能处理其他任务

using (var fileStream = File.Create("C:\\lindexi\\File.txt"))
{
    await iputStream.CopyToAsync(fileStream);
}

2. 可控制复制的缓存大小的方法

下面这种方法可控制复制的缓存大小

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}
 
// 使用方法如下
using (Stream file = File.Create("C:\\lindexi\\File.txt"))
{
    CopyStream(input, file);
}

缓存大小可修改 new byte[1024] 的值
3. 一些不推荐的方法

using (var stream = new MemoryStream())
{
    input.CopyTo(stream);
    File.WriteAllBytes(file, stream.ToArray());
}

上面这个方法将会复制两次内存,而且如果 input 这个资源长度有 1G 就要占用 2G 的资源

public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;
 
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
 
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}

下面是一个超级慢的方法,一个 byte 一个 byte 写入的速度是超级慢的

public void SaveStreamToFile(Stream stream, string filename)
{  
   using(Stream destination = File.Create(filename))
   {
       Write(stream, destination);
   }
}
public void Write(Stream from, Stream to)
{
      for(int a = from.ReadByte(); a != -1; a = from.ReadByte())
      {
      	to.WriteByte( (byte) a );
      }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcj_cq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值