当前位置:   article > 正文

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

c# memorystream保存文件

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5

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

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

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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

using (var stream = new MemoryStream())
{
    input.CopyTo(stream);
    File.WriteAllBytes(file, stream.ToArray());
}
  • 1
  • 2
  • 3
  • 4
  • 5

上面这个方法将会复制两次内存,而且如果 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);
     }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

下面是一个超级慢的方法,一个 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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/367405
推荐阅读
相关标签
  

闽ICP备14008679号