1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Reflection; 5 using System.Text; 6 7 namespace IO目錄管理 8 { 9 class Program 10 { 11 private string _StrSourcePath = @"C:\Users\MO\Desktop\1.txt"; //源文件目錄 12 private string _StrTagrgetPath = @"C:\Users\MO\Desktop\2.txt"; //目標文件目錄 13 public void Test() 14 { 15 //路徑合法性判斷 16 if (File.Exists(_StrSourcePath)) 17 { 18 //構造讀取文件流對象 19 using (FileStream fsRead = new FileStream(_StrSourcePath, FileMode.Open)) //打開文件,不能創建新的 20 { 21 //構建寫文件流對象 22 using (FileStream fsWrite = new FileStream(_StrTagrgetPath, FileMode.Create)) //沒有找到就創建 23 { 24 //開辟臨時緩存內存 25 byte[] byteArrayRead = new byte[1024 * 1024]; // 1字節*1024 = 1k 1k*1024 = 1M內存 26 27 //通過死緩存去讀文本中的內容 28 while (true) 29 { 30 //readCount 這個是保存真正讀取到的字節數 31 int readCount = fsRead.Read(byteArrayRead, 0, byteArrayRead.Length); 32 33 //開始寫入讀取到緩存內存中的數據到目標文本文件中 34 fsWrite.Write(byteArrayRead, 0, readCount); 35 36 37 //既然是死循環 那么什么時候我們停止讀取文本內容 我們知道文本最后一行的大小肯定是小於緩存內存大小的 38 if (readCount < byteArrayRead.Length) 39 { 40 break; //結束循環 41 } 42 } 43 } 44 } 45 } 46 else 47 { 48 Console.WriteLine("源路徑或者目標路徑不存在。"); 49 } 50 } 51 52 static void Main(string[] args) 53 { 54 Program p = new Program(); 55 p.Test(); 56 Console.ReadKey(); 57 58 } 59 } 60 }