C#使用FileStream读写文件


            #region 使用FileStream读取数据
            using (FileStream fsRead = new FileStream(@"C:\Users\Administrator\Desktop\2.txt", FileMode.OpenOrCreate, FileAccess.Read))
            {
                //创建缓冲区的大小

                byte[] buffer = new byte[fsRead.Length];
                //这次读取实际读到的字节数
                int r = fsRead.Read(buffer, 0, buffer.Length);

                //将字节数组转换成字符串
                string str = System.Text.Encoding.Default.GetString(buffer);
                Console.WriteLine(str);
            }
            Console.ReadKey();
            #endregion



            #region 使用FileStream来写入数据
            using (FileStream fsWrite = new FileStream(@"C:\Users\Administrator\Desktop\2.txt", FileMode.Append, FileAccess.Write))
            {
                string str = "哈哈哈哈哈";
                //将字符串转换成字节数组
                byte[] buffer = System.Text.Encoding.GetEncoding("gbk").GetBytes(str);
                fsWrite.Write(buffer, 0, buffer.Length);
                Console.WriteLine("写入OK");
            }
            Console.ReadKey();
            #endregion

 

你可能感兴趣的:(C#)