using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { //思路:就是現將要賦值的多媒體文件讀取出來,然后希望如到你制定的位置 string source = @"D:\教程\1.txt"; string target = @"D:\教程\2.txt"; CopyFile(source, target); Console.WriteLine("Copy Complete!"); Console.ReadKey(); } public static void CopyFile(string source,string target) { //1。我們創建一個負責讀取的流 fsRead using(FileStream fsRead = new FileStream(source,FileMode.OpenOrCreate,FileAccess.Read)) //使用using語句減免代碼,FileStream(src,mode,acs),節省Close() & Dispose() { //2.創建一個負責寫入的流 fsWrite using(FileStream fsWrite = new FileStream(target,FileMode.OpenOrCreate,FileAccess.Write)) //使用using語句減免代碼,FileStream(src,mode,acs), 節省Close() & Dispose(),兩個using嵌套,內部先Close() & Dispose() { byte[] buffer = new byte[1024*1024*5]; //因為文件可能會比較大,所以我們在讀取的時候,應該通過一個循環去讀取 while (true)//循環去讀取寫入 { //返回本次實際讀取到的字節數 int r = fsRead.Read(buffer, 0, buffer.Length); //讀取 //如果返回一個0,也就意味着什么都沒有讀取到,表示讀取完了 if (r == 0) { break; } fsWrite.Write(buffer,0,r); //寫入 } } } } } }
