- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace _06文件流
- {
- class Program
- {
- static void Main(string[] args)
- {
- //使用FileStream来读取数据
- FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Read);
- byte[] buffer = new byte[1024 * 1024 * 5];
- //3.8M 5M
- //返回本次实际读取到的有效字节数
- int r = fsRead.Read(buffer, 0, buffer.Length);
- //将字节数组中每一个元素按照指定的编码格式解码成字符串
- string s = Encoding.UTF8.GetString(buffer, 0, r);
- //关闭流
- fsRead.Close();
- //释放流所占用的资源
- fsRead.Dispose();
- Console.WriteLine(s);
- Console.ReadKey();
- //使用FileStream来写入数据
- //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write))
- //{
- // string str = "看我游牧又把你覆盖掉";
- // byte[] buffer = Encoding.UTF8.GetBytes(str);
- // fsWrite.Write(buffer, 0, buffer.Length);
- //}
- //Console.WriteLine("写入OK");
- //Console.ReadKey();
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- namespace _07使用文件流来实现多媒体文件的复制
- {
- class Program
- {
- static void Main(string[] args)
- {
- //思路:就是先将要复制的多媒体文件读取出来,然后再写入到你指定的位置
- string source = @"C:\Users\SpringRain\Desktop\1、复习.wmv";
- string target = @"C:\Users\SpringRain\Desktop\new.wmv";
- CopyFile(source, target);
- Console.WriteLine("复制成功");
- Console.ReadKey();
- }
- public static void CopyFile(string soucre, string target)
- {
- //1、我们创建一个负责读取的流
- using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read))
- {
- //2、创建一个负责写入的流
- using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
- {
- 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);
- }
- }
- }
- }
- }
- }