C#FileStream文件流(字符)
2016-02-24 20:52
585 查看
使用FileStream需要导入命名空间:using
System.IO;
将创建文件流对象的过程写在using当中,会自动的帮助我们释放流所占用的资源。
System.IO;
将创建文件流对象的过程写在using当中,会自动的帮助我们释放流所占用的资源。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { 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 fsWrite1 = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write)) { string str = "看我游牧又把你覆盖掉"; byte[] buffer1 = Encoding.UTF8.GetBytes(str); fsWrite1.Write(buffer1, 0, buffer1.Length); } Console.WriteLine("写入OK"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { 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); } } } } } }
相关文章推荐
- C#高级编程(三)
- 如何有效的使用C#读取文件
- 【C#】Color颜色对照表
- C#之构造方法
- C# 结构的特点
- C#-StructLayoutAttribute(结构体布局)
- C#中的IntPtr类型
- C#将一个excel工作表根据指定范围拆分为多个excel文件
- C# DataTable Compute方法的使用
- C#访问openfire服务器之一:服务端的安装、客户端的简介
- C#调用金数据API
- C#访问openfire服务器之三:一次成功的登录
- C#原理
- C# using 三种使用方式
- C#怎么设置子窗体在主窗体中居中显示
- C#进阶系列——WebApi接口测试工具:WebApiTestClient
- C#创建唯一的订单号, 考虑时间因素
- C# 串口通讯
- C# DateTime详解
- c# virtual详解