文件流,文件流的练习.
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //使用FileStream来读取数据 6 FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Read); 7 byte[] buffer = new byte[1024 * 1024 * 5]; 8 //3.8M 5M 9 //返回本次实际读取到的有效字节数 10 int r = fsRead.Read(buffer, 0, buffer.Length); 11 //将字节数组中每一个元素按照指定的编码格式解码成字符串 12 string s = Encoding.UTF8.GetString(buffer, 0, r); 13 //关闭流 14 fsRead.Close(); 15 //释放流所占用的资源 16 fsRead.Dispose(); 17 Console.WriteLine(s); 18 Console.ReadKey(); 19 20 21 22 //使用FileStream来写入数据 23 //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write)) 24 //{ 25 // string str = "看我游牧又把你覆盖掉"; 26 // byte[] buffer = Encoding.UTF8.GetBytes(str); 27 // fsWrite.Write(buffer, 0, buffer.Length); 28 //} 29 //Console.WriteLine("写入OK"); 30 //Console.ReadKey(); 31 } 32 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //思路:就是先将要复制的多媒体文件读取出来,然后再写入到你指定的位置 6 string source = @"C:\Users\SpringRain\Desktop\1、复习.wmv"; 7 string target = @"C:\Users\SpringRain\Desktop\new.wmv"; 8 CopyFile(source, target); 9 Console.WriteLine("复制成功"); 10 Console.ReadKey(); 11 } 12 13 public static void CopyFile(string soucre, string target) 14 { 15 //1、我们创建一个负责读取的流 16 using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read)) 17 { 18 //2、创建一个负责写入的流 19 using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write)) 20 { 21 byte[] buffer = new byte[1024 * 1024 * 5]; 22 //因为文件可能会比较大,所以我们在读取的时候 应该通过一个循环去读取 23 while (true) 24 { 25 //返回本次读取实际读取到的字节数 26 int r = fsRead.Read(buffer, 0, buffer.Length); 27 //如果返回一个0,也就意味什么都没有读取到,读取完了 28 if (r == 0) 29 { 30 break; 31 } 32 fsWrite.Write(buffer, 0, r); 33 } 34 } 35 } 36 } 37 38 39 }

浙公网安备 33010602011771号