The abstract Stream class is the base for all streams. It defines methods and properties for three fundamental operations :
reading, writing, and
seeking , as well as for administrative tasks such as closing , flushing, and configuring timeouts.
Reading:
Code
/**//// <summary>
/// 从当前流读取序列字节,并且将次流的位置提升 count 个字节数.
/// </summary>
/// <param name="buffer">字节数组</param>
/// <param name="offset">buffer字节数组的读取位置</param>
/// <param name="count">读取的字节数量</param>
/// <returns></returns>
public abstract int Read(byte[] buffer, int offset,int count)
/**////<summary>
/// 从流中读取一个字节,并将流内的位置向前推进一个字节,或者如果已到达流的末尾,则返回 -1
///</summary>
public virtual int ReadByte();
例子:
Code
// 创建一个test.txt在当前路径下, test.txt 中的内容是 12345678
using (var stream =new FileStream("test.txt",FileMode.OpenOrCreate))
{
var block = new byte[stream.Length];
Console.WriteLine(stream.ReadByte()); // 49 //每次读一次 Position 的值自动加1
Console.WriteLine(stream.ReadByte()); // 50
stream.Position = 0; // 把流位置设置为起始位置,经过上面 两行代码, Position 的值是2
Console.WriteLine(stream.Read(block,0,block.Length)); //8
Console.WriteLine(stream.Read(block, 0, block.Length)); //0 因为 Position 已经到了末尾
}