Stream 和 Byte[]互操作
在.Net的IO操作中经常会用到Stream和Byte[],有两种形式:
一.Stream->Byte[]:
1.如果Stream的 Length属性可读,非常的简单,代码如下:
1 private byte[] GetBytes(Stream stream)
2 {
3 if (stream.CanSeek)
4 {
5 Byte[] buffer = new byte[stream.Length];
6 stream.Write(buffer, 0, buffer.Length);
7 return buffer;
8 }
9 //用下面的方法
10 return null;
11 }
2 {
3 if (stream.CanSeek)
4 {
5 Byte[] buffer = new byte[stream.Length];
6 stream.Write(buffer, 0, buffer.Length);
7 return buffer;
8 }
9 //用下面的方法
10 return null;
11 }
2.如果Stream的 Length属性不可读,代码如下:
1 private byte[] GetBytes(Stream stream)
2 {
3 using (MemoryStream mstream = new MemoryStream())
4 {
5 byte[] bytes = new byte[1024]; //此处不易设置太大或太小的值,且应该为2的次方
6 if (stream.CanRead)
7 {
8 while (true)
9 {
10 int length = stream.Read(bytes, 0, bytes.Length);
11 if (length <= 0)
12 {
13 break;
14 }
15 mstream.Write(bytes, 0, length);
16 }
17 }
18 return mstream.ToArray();
19 }
20 }
21
二.bytes-Stream:2 {
3 using (MemoryStream mstream = new MemoryStream())
4 {
5 byte[] bytes = new byte[1024]; //此处不易设置太大或太小的值,且应该为2的次方
6 if (stream.CanRead)
7 {
8 while (true)
9 {
10 int length = stream.Read(bytes, 0, bytes.Length);
11 if (length <= 0)
12 {
13 break;
14 }
15 mstream.Write(bytes, 0, length);
16 }
17 }
18 return mstream.ToArray();
19 }
20 }
21
直接使用内存流即可,代码如下:
MemoryStream ms=new MemoryStream(bytes)