一、读取文件
static void Main(string[] args) { FileStream fileStream = new FileStream(@"C:UsersasusDesktop新建文本文档 (4).txt", FileMode.OpenOrCreate, FileAccess.Read); //每次读取数据流大小 byte[] buffer = new byte[1024 * 1024 * 5]; //返回本次实际读取的字节数 var r = fileStream.Read(buffer, 0, buffer.Length); //将字节数组中的每个元素按照规定的编码格式转化为字符串 string s = Encoding.UTF8.GetString(buffer, 0, r); fileStream.Close(); //释放流占的资源 fileStream.Dispose(); Console.WriteLine(s); Console.ReadKey(); }
二写入文件
static void Main(string[] args) { //使用FileStream写字节 using (FileStream fileStream=new FileStream(@"C:UsersasusDesktop新建文本文档 (4).txt", FileMode.OpenOrCreate, FileAccess.Write)) { string str = "把我写进文本中"; byte[] buffer = Encoding.UTF8.GetBytes(str); fileStream.Write(buffer, 0, buffer.Length); } Console.WriteLine("写入成功"); Console.ReadKey(); }