本文實例講述了C#使用FileStream循環讀取大文件數據的方法。分享給大家供大家參考,具體如下:
今天學習了FileStream的用法,用來讀取文件流,教程上都是讀取小文件,一次性讀取,但是如果遇到大文件,那么我們就需要循環讀取文件。
直接上代碼。
引用命名空間
using System.IO;
下面就是循環讀取大文件的代碼
class Program{ static void Main(string[] args) { //循環讀取大文本文件 FileStream fsRead; //獲取文件路徑 string filePath="C://Users//國興//Desktop//1號店賬號.txt"; //用FileStream文件流打開文件 try { fsRead = new FileStream(@filePath,FileMode.Open); } catch (Exception) { throw; } //還沒有讀取的文件內容長度 long leftLength = fsRead.Length; //創建接收文件內容的字節數組 byte[] buffer = new byte[1024]; //每次讀取的最大字節數 int maxLength=buffer.Length; //每次實際返回的字節數長度 int num=0; //文件開始讀取的位置 int fileStart=0; while (leftLength>0) { //設置文件流的讀取位置 fsRead.Position=fileStart; if (leftLength<maxLength) { num=fsRead.Read(buffer,0,Convert.ToInt32(leftLength)); } else{ num=fsRead.Read(buffer,0,maxLength); } if (num==0) { break; } fileStart += num; leftLength -= num; Console.WriteLine(Encoding.Default.GetString(buffer)); } Console.WriteLine("end of line"); fsRead.Close(); Console.ReadKey(); }}
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答