stream的神奇
流(stream):是所有流的抽象基类,是一组连续的,有顺序的字节序列,例如:文件流(filestream),i/o流,内部进程通信管道(PipeException),tcp/ip套接字(NetworkStream,Socket),内存流(MemoryStream ),我们在用流进行文件读写的时候,数据流会先进入缓冲区,然后再写入基类流。注意:流在使用完了之后一定要关闭。
//用流的操作在文件的指定位置插入字符: //通过file的open()方法返回一个文件流, FileStream fs = File.Open(@"E:\7.13.txt",FileMode.Open ); byte[] b = Encoding.UTF8.GetBytes("我们"); //通过流的position属性和writebyte()方法实现在文件指定位置插入字符串 fs.Position = 5; foreach (byte bb in b) { fs.WriteByte(bb); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication29 { //通过流的position属性和seek()方法对数据进行重新定位 class Program { static void Main(string[] args) { string str = "hello world welcome to china"; byte[] b = null; string s=""; MemoryStream ms = new MemoryStream(); if (ms.CanWrite) { //将指定的字符串转化成字节数组 b= Encoding.Default.GetBytes(str); //foreach (byte bb in b) //{ // Console.WriteLine(bb); //} //将字节数组写入流中 ms.Write(b,0,5); Console.WriteLine(ms.Length +" "+ms.Position +1); } //通过流的canseek()方法判断当前流是否支持查找,然后通过流的seek()方法进行重新定位 long newposi = ms.CanSeek ? ms.Seek(3, SeekOrigin.Current) : 0; //重新定位后如果流的位置小于字节流的长度,则以重新定位后的流的长度设为偏移量重新写入 if (newposi < b.Length) { ms.Write(b,(int)newposi ,b.Length -(int)newposi ); Console.WriteLine(ms.Position + 1); } ms.Position = 0; byte[] b1 = new byte[ms.Length]; int result = ms.CanRead?ms.Read(b1,0,b1.Length ):0; //获取读取字符的长度 int charcount = Encoding.Default.GetCharCount(b1,0,result ); char[] c = new char[charcount]; //将读到的字节转化成字符,并循环遍历访问 Encoding.Default.GetDecoder().GetChars(b1, 0, result, c, 0); for (int i = 0; i < c.Length ; i++) { s+=c[i]; } Console.WriteLine(s); ms.Close(); Console.ReadLine(); } } }