using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO;//流namespace Stream{ class Program { static void Main(string[] args) { Stream2(); Console.ReadKey(); } static void Stream1() { string filePath = "D:\\test.txt"; //利用File.Open创建一个FileStream实体 using (FileStream filestream = File.Open(filePath, FileMode.Open)) { //定义字符串 string msg = "hello world";//string msg =Console.ReadLine(); //将字符串转化为字节数据 byte[] msgAsByteArray = Encoding.Default.GetBytes(msg); Console.WriteLine("开始写入到文件中{0}", msg); //将字节数据写入到流中 filestream.Write(msgAsByteArray, 0, msgAsByteArray.Length); //重置流中的位置 filestream.Seek(0, SeekOrigin.Begin); Console.WriteLine("写入文件中的数据为:"); //定义字节数组 byte[] bytesFormFile = new byte[msgAsByteArray.Length]; //从流中读取到字节数据 filestream.Read(bytesFormFile, 0, msgAsByteArray.Length); Console.WriteLine(Encoding.Default.GetString(bytesFormFile)); } } ////// StreamWriter与StreamReader /// static void Stream2() { string filePath = "D:\\test.txt"; using (FileStream filestream = File.Open(filePath, FileMode.Open)) { //定义字符串 string msg = "hello world(你好)";//string msg =Console.ReadLine(); //创建StreamWriter对象System.Text.Encoding.Default:编码格式 StreamWriter streamwriter = new StreamWriter(filestream,System.Text.Encoding.Default); Console.WriteLine("开始写入{0}到文件中", msg); streamwriter.Write(msg); //创建StreamReader对象 StreamReader streamreader = new StreamReader(filestream, Encoding.Default); //输出 Console.WriteLine("写入到文件中数据为{0}", streamreader.ReadLine()); //关闭 streamwriter.Close(); streamreader.Close(); } } }}
Stream继承结构: