日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C#?將?Stream?保存到文件的方法_C#教程

作者:※※冰馨※※ ? 更新時(shí)間: 2022-10-01 編程語(yǔ)言

在拿到一個(gè) Stream 如何優(yōu)雅將這個(gè) Stream 保存到代碼

最優(yōu)雅的方法應(yīng)該是通過(guò) CopyTo 或 CopyToAsync 的方法

using (var fileStream = File.Create("C:\\lindexi\\File.txt"))
{
    inputStream.Seek(0, SeekOrigin.Begin);
    iputStream.CopyTo(fileStream);
}

這里的?inputStream.Seek(0, SeekOrigin.Begin);?不一定需要,請(qǐng)根據(jù)你自己的需求,如你只需要將這個(gè) Stream 的從第10個(gè)byte開(kāi)始復(fù)制等就不能采用這句代碼

用異步方法會(huì)讓本次寫入的時(shí)間長(zhǎng)一點(diǎn),但是會(huì)讓總體性能更好,讓 CPU 能處理其他任務(wù)

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

注意使用 CopyToAsync 記得加上 await 哦,執(zhí)行到這句代碼的時(shí)候,就將執(zhí)行交給了 IO 了,大部分的 IO 處理都不需要 CPU 進(jìn)行計(jì)算,這樣能達(dá)到總體性能更好

另外如果 iputStream 是外面?zhèn)魅氲模敲次也唤ㄗh在這個(gè)方法里面釋放,為什么呢?我用的好好的一個(gè)Stream傳入一個(gè)業(yè)務(wù)就被干掉了

其次的方法是自己控制內(nèi)存復(fù)制緩存,此方法將會(huì)多出一次內(nèi)存復(fù)制

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]?的值,讓你可以控制復(fù)制的緩存

接下來(lái)就是一些不推薦的方法了,但是寫的時(shí)候方便

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

上面這個(gè)方法將會(huì)復(fù)制兩次內(nèi)存,而且如果 input 這個(gè)資源長(zhǎng)度有 1G 就要占用 2G 的資源

和上面差不多的是申請(qǐng)一個(gè)大的緩存,如下面代碼:

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);
     }
}

從效率和代碼的優(yōu)雅其實(shí)都不如 CopyTo 方法,而且因?yàn)?stream.Length 作為長(zhǎng)度沒(méi)有決定緩存,所以也不如第二個(gè)方法

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 );
      }
}

原文鏈接:https://blog.csdn.net/Pei_hua100/article/details/126159850

欄目分類
最近更新