代码改变世界

Stream 和Byte[] 之间的转换

2010-07-13 18:05  calm_水手  阅读(166)  评论(0编辑  收藏  举报
代码
 1 //Stream 和Byte[]之间的转换
 2 byte[] arr=new byte[stream.Length];//设定arr长度
 3 
 4 stream.Read(arr,0,arr.Length);//stream从arr中读取数据
 5 
 6 //提供表示流中的参考点以供进行查找的字段,设置当前流中的位置。
 7 stream.Seek(0,SeekOrigin.Begin);
 8  
 9 return arr;
10 
11 
12 //将byte[] 转换成Stream 利用内存
13 Stream stream=new MemoryStream(arr);
14 return stream;
15 
16 /* - - - - - - - - - - - - - - - - - - - - - - - - 
17  * Stream 和 文件之间的转换
18  * - - - - - - - - - - - - - - - - - - - - - - - */
19 /// <summary>
20 /// 将 Stream 写入文件
21 /// </summary>
22 public void StreamToFile(Stream stream,string fileName)
23 {
24     // 把 Stream 转换成 byte[]
25     byte[] bytes = new byte[stream.Length];
26     stream.Read(bytes, 0, bytes.Length);
27     // 设置当前流的位置为流的开始
28     stream.Seek(0, SeekOrigin.Begin);
29 
30     // 把 byte[] 写入文件
31     FileStream fs = new FileStream(fileName, FileMode.Create);
32     BinaryWriter bw = new BinaryWriter(fs);
33     bw.Write(bytes);
34     bw.Close();
35     fs.Close();
36 }
37 
38 /// <summary>
39 /// 从文件读取 Stream
40 /// </summary>
41 public Stream FileToStream(string fileName)
42 {            
43     // 打开文件
44     FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
45     // 读取文件的 byte[]
46     byte[] bytes = new byte[fileStream.Length];
47     fileStream.Read(bytes, 0, bytes.Length);
48     fileStream.Close();
49     // 把 byte[] 转换成 Stream
50     Stream stream = new MemoryStream(bytes);
51     return stream;
52 }

  文章参考:http://www.cnblogs.com/anjou/archive/2007/12/07/986887.html?login=1#commentform ,在此对作者表示感谢!