using System;using System.Collections.Generic;using System.Text;using System.IO; namespace _5_1{ class Program { static void Main(string[] args) { Stream s = null; try { s = new MemoryStream(); writestream(s); readstream(s); Console.WriteLine("-------------------"); bulkwritestream(s); bulkreadstream(s); seekstream(s); } finally { s.Close(); } } private static void writestream(Stream s) //向流中一个字节一个字节(这里写入的是整数,必须小于256)写入数据。 { for (int i = 0; i < 10; i++) s.WriteByte((byte)i); } private static void readstream(Stream s) //从流中读入之前写入的字节 { s.Position = 0; //写的过程中,流的位置已经到了流的末尾,理所当然,读的时候,要把流的位置放在流的最前面,顺着读嘛。(倒着读就不用了,后面有) int i = 0; while ((i = s.ReadByte()) != -1) // 到流的末端返回-1 { Console.WriteLine(i); } } private static void bulkreadstream(Stream s) //这里读取流中所有数据到 一个数组中。 { s.Position = 0; byte[] arr = new byte[s.Length]; //存放流中数据的数组 int bytesread = 0; int bytes2read = (int)s.Length; //流的长度,需要读取的字节数,在这里是整个流中的字节数。 while (bytes2read > 0) { int val = s.Read(arr, bytesread, bytes2read); //第一个参数是要读取到的目标数组(从流中读取数据),第二个是已经读取的字节数,第三个参数是还需要读取的字节数 //val返回值是读取字节数,如果到达流的末端,则为0 Console.WriteLine("------"+"val="+val+"-----"); //可以测试下val的值 if (val == 0) break; bytes2read -= val; bytesread += val; } for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); //if (i > 0 && i % 20 == 0) //每行显示20个数字 // Console.WriteLine(); } Console.WriteLine(); } private static void bulkwritestream(Stream s) //向当前流中写入字节序列 { s.Position = 0; byte[] bytes = new byte[10] { 10,20,30,40,50,60,70,80,90,100}; s.Write(bytes, 0, 10); s.Flush(); //不知道有什么用????? } private static void seekstream(Stream s) //从流的后面往前面读取流中数据 { long start = -1; while (s.Position != 1) { Console.WriteLine("s 所在位置:"+s.Position ); long position = s.Seek(start, SeekOrigin.End); Console.WriteLine(s.ReadByte()); --start; } } }}

评论