当前位置:编程学习 > asp >>

.Net那点事儿系列:System.IO之Stream

 

Stream在msdn的定义:提供字节序列的一般性视图(provides a generic view of a sequence of bytes)。这个解释太抽象了,不容易理解;从stream的字面意思“河,水流”更容易理解些,stream是一个抽象类,它定义了类似“水流”的事物的一些统一行为,包括这个“水流”是否可以抽水出来(读取流内容);是否可以往这个“水流”中注水(向流中写入内容);以及这个“水流”有多长;如何关闭“水流”,如何向“水流”中注水,如何从“水流”中抽水等“水流”共有的行为。

 

常用的Stream的子类有:

 

1)MemoryStream 存储在内存中的字节流

 

2)FileStream  存储在文件系统的字节流

 

3)NetworkStream 通过网络设备读写的字节流

 

4)BufferedStream 为其他流提供缓冲的流

 

Stream提供了读写流的方法是以字节的形式从流中读取内容。而我们经常会用到从字节流中读取文本或者写入文本,微软提供了StreamReader和StreamWriter类帮我们实现在流上读写字符串的功能。

 

下面看下如何操作Stream,即如何从流中读取字节序列,如何向流中写字节

 

1. 使用Stream.Read方法从流中读取字节,如下示例注释:

 

view sourceprint?01 using System; 

 

02 using System.Collections.Generic; 

 

03 using System.Linq; 

 

04 using System.Text; 

 

05 using System.IO; 

 

06   

 

07 namespace UseStream 

 

08 { 

 

09     class Program 

 

10     { 

 

11         //示例如何从流中读取字节流 

 

12         static void Main(string[] args) 

 

13         { 

 

14             var bytes = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4,(byte)5,(byte)6,(byte)7,(byte)8}; 

 

15             using (var memStream = new MemoryStream(bytes)) 

 

16             { 

 

17                 int offset = 0; 

 

18                 int readOnce = 4; 

 

19                   

 

20                 do

 

21                 { 

 

22                     byte[] byteTemp = new byte[readOnce]; 

 

23                     // 使用Read方法从流中读取字节 

 

24                     //第一个参数byte[]存储从流中读出的内容 

 

25                     //第二个参数为存储到byte[]数组的开始索引, 

 

26                     //第三个int参数为一次最多读取的字节数  

 

27                     //返回值是此次读取到的字节数,此值小于等于第三个参数 

 

28                     int readCn = memStream.Read(byteTemp, 0, readOnce); 

 

29                     for (int i = 0; i < readCn; i++) 

 

30                     { 

 

31                         Console.WriteLine(byteTemp[i].ToString()); 

 

32                     } 

 

33                       

 

34                     offset += readCn; 

 

35   

 

36                     //当实际读取到的字节数小于设定的读取数时表示到流的末尾了 

 

37                     if (readCn < readOnce) break; 

 

38                 } while (true); 

 

39             } 

 

40   

 

41             Console.Read(); 

 

42         } 

 

43     } 

 

44 }

 

 

2. 使用Stream.BeginRead方法读取FileStream的流内容

 

注意:BeginRead在一些流中的实现和Read完全相同,比如MemoryStream;而在FileStream和NetwordStream中BeginRead就是实实在在的异步操作了。

 

如下示例代码和注释:

 

view sourceprint?01 using System; 

 

02 using System.Collections.Generic; 

 

03 using System.Linq; 

 

04 using System.Text; 

 

05 using System.IO; 

 

06 using System.Threading; 

 

07   

 

08 namespace UseBeginRead 

 

09 { 

 

10     class Program 

 

11     { 

 

12         //定义异步读取状态类 

 

13         class AsyncState 

 

14         { 

 

15         &

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,