C# FileStream MemoryStream BufferedStream StreamReader StreamWriter

FileStream读取文件

FileStream file =File.Open(@"F:\file.txt",FileMode.Open);//初始化文件流byte[] array =newbyte[file.Length];//初始化字节数组file.Read(array,0, array.Length);//读取流中数据把它写到字节数组中file.Close();//关闭流string str =Encoding.Default.GetString(array);//将字节数组内容转化为字符串Console.WriteLine(str); FileStream写入文件
FileStream file =File.Open(@"F:\file.txt",FileMode.Append);//初始化文件流byte[] array =Encoding.UTF8.GetBytes("Hello World!你好");//给字节数组赋值file.Write(array,0, array.Length);//将字节数组写入文件流file.Close();//关闭流
MemoryStream解析数据
string str ="Hi!你好!"; byte[] array =Encoding.UTF8.GetBytes(str);//将字符串转化为字节数组MemoryStream memory =newMemoryStream(array);//初始化MemoryStream类byte[] arrayNew = memory.ToArray();//将内存中的数据转换为字节数组string strNew =Encoding.UTF8.GetString(arrayNew);//将字节数组转换为字符串
 BufferedStream封装流 FileStream file1 =File.Open(@"F:\file1.txt",FileMode.OpenOrCreate,FileAccess.Read);//读取文件流 FileStream file 2=File.Open(@"F:\file2.txt",FileMode.OpenOrCreate,FileAccess.Write);//写入文件流  byte[] array =newbyte[4096];  BufferedStream bufferedInput =newBufferedStream(file1);//封装文件流 BufferedStream bufferedOutput =newBufferedStream(file2);//封装文件流   bufferedInput.Read(array,0, array.Length);  bufferedOutput.Write(array,0, array.Length);  int bytesRead =0; while((bytesRead = bufferedInput.Read(array,0,4096))>0)//读取到了数据 {      bufferedOutput.Write(array,0, bytesRead); Console.WriteLine(bytesRead); }  bufferedInput.Close();//关闭各种流  bufferedOutput.Close();  file1.Close();  file2.Close();

StreamReader/Writer读写 StreamReader reader =newStreamReader("filePath");//初始化读取 StreamWriter writer =newStreamWriter("filePath");//初始化写入 string readStr=reader.ReadLine();//从流中读取一行 string readAff = reader.ReadToEnd();//从流中读取全部 writer.Write("Hi 你好");//写入内容 writer.WriteLine("Hi 你好");//写入一行 reader.Close();//关闭流 writer.Close();
posted @ 2013-12-06 21:55  Cad人生  阅读(1542)  评论(0编辑  收藏  举报