C# FileStream復(fù)制大文件功能
FileStream緩沖讀取和寫入可以提高性能。每次復(fù)制文件的一小段,以節(jié)省總內(nèi)存開銷。當(dāng)然,本機復(fù)制也可以采用.NET內(nèi)部的System.IO.File.Copy方法。
FileStream讀取文件的時候,是先講流放入內(nèi)存,經(jīng)Flash()方法后將內(nèi)存中(緩沖中)的數(shù)據(jù)寫入文件。如果文件非常大,勢必消耗性能。特封裝在FileHelper中以備不時之需。強制類型轉(zhuǎn)換,如果文件很大,比如4G,就會出現(xiàn)溢出的情況,復(fù)制的結(jié)果字節(jié)丟失嚴重,導(dǎo)致復(fù)制文件和源文件大小不一樣。這里修改的代碼如下:
public static class FileHelper { /// <summary> /// 復(fù)制大文件 /// </summary> /// <param name="fromPath">源文件的路徑</param> /// <param name="toPath">文件保存的路徑</param> /// <param name="eachReadLength">每次讀取的長度</param> /// <returns>是否復(fù)制成功</returns> public static bool CopyFile(string fromPath, string toPath, int eachReadLength) { //將源文件 讀取成文件流 FileStream fromFile = new FileStream(fromPath, FileMode.Open, FileAccess.Read); //已追加的方式 寫入文件流 FileStream toFile = new FileStream(toPath, FileMode.Append, FileAccess.Write); //實際讀取的文件長度 int toCopyLength = 0; //如果每次讀取的長度小于 源文件的長度 分段讀取 if (eachReadLength < fromFile.Length) { byte[] buffer = new byte[eachReadLength]; long copied = 0; while (copied <= fromFile.Length - eachReadLength) { toCopyLength = fromFile.Read(buffer, 0, eachReadLength); fromFile.Flush(); toFile.Write(buffer, 0, eachReadLength); toFile.Flush(); //流的當(dāng)前位置 toFile.Position = fromFile.Position; copied += toCopyLength; } int left = (int)(fromFile.Length - copied); toCopyLength = fromFile.Read(buffer, 0, left); fromFile.Flush(); toFile.Write(buffer, 0, left); toFile.Flush(); } else { //如果每次拷貝的文件長度大于源文件的長度 則將實際文件長度直接拷貝 byte[] buffer = new byte[fromFile.Length]; fromFile.Read(buffer, 0, buffer.Length); fromFile.Flush(); toFile.Write(buffer, 0, buffer.Length); toFile.Flush(); } fromFile.Close(); toFile.Close(); return true; } }
測試代碼:
class Program { static void Main(string[] args) { Stopwatch watch = new Stopwatch(); watch.Start(); if (FileHelper.CopyFile(@"D:\安裝文件\新建文件夾\SQLSVRENT_2008R2_CHS.iso", @"F:\SQLSVRENT_2008R2_CHS.iso", 1024 * 1024 * 5)) { watch.Stop(); Console.WriteLine("拷貝完成,耗時:" + watch.Elapsed.Seconds + "秒"); } Console.Read(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# OleDbDataReader快速數(shù)據(jù)讀取方式(3種)
這篇文章主要介紹了C# OleDbDataReader快速數(shù)據(jù)讀取方式(3種),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12C#使用FluentHttpClient實現(xiàn)請求WebApi
FluentHttpClient 是一個REST API 異步調(diào)用 HTTP 客戶端,調(diào)用過程非常便捷,下面我們就來學(xué)習(xí)一下C#如何使用FluentHttpClient實現(xiàn)請求WebApi吧2023-12-12