C#的Byte[]和stream
1、Byte[]
=====
1. BitConverter
将基础数据类型与字节数组相互转换。注意string不是基础类型,而且该方法在不同平台间传递可能有误。
- int i = 13;
- byte[] bs = BitConverter.GetBytes(i);
- Console.WriteLine(BitConverter.ToInt32(bs, 0));
2. Encoding
注意慎用Encoding.Default,其值取自操作系统当前的设置,因此在不同语言版本的操作系统是不相同的。建议使用UTF8或者GetEncoding(”gb2312″)。
- string s = "abc";
- byte[] bs = Encoding.UTF8.GetBytes(s);
- Console.WriteLine(Encoding.UTF8.GetString(bs));
3. BinaryFormatter
以二进制格式将对象或整个连接对象图形序列化和反序列化。
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- [Serializable]
- class Data
- {
- private int x = 13;
- public void Test()
- {
- Console.WriteLine(x);
- }
- }
- static void Main(string[] args)
- {
- Data data = new Data();
- MemoryStream stream = new MemoryStream();
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, data);
- byte[] bs = stream.ToArray();
- MemoryStream stream2 = new MemoryStream(bs);
- Data data2 = (Data)formatter.Deserialize(stream2);
- data2.Test();
- }
2、Stream
=====
Stream 包含 FileStream、MemoryStream、BufferedStream、NetworkStream、CryptoStream。
常用的方法和属性包括:Close / Flush / Seek / Read / Write / CanSeek等,可参考SDK。
Stream 并不能直接操作基元和对象类型,需要将其转换成Byte[]才能进行读写操作。以下记录几种转换方式。
- byte[] bs = Encoding.UTF8.GetBytes("abc");
- // 1. Byte[] to Stream
- MemoryStream stream = new MemoryStream(bs);
- // 2. Byte[] to Stream
- MemoryStream stream2 = new MemoryStream();
- stream2.Write(bs, 0, bs.Length);
- // 3. Byte[] to Stream
- FileStream stream3 = new FileStream("a.dat", FileMode.Create, FileAccess.ReadWrite);
- stream3.Write(bs, 0, bs.Length);
- stream3.Close();
- // 4. Stream to Byte[]
- byte[] bs2 = stream.ToArray();
- // 5. Stream to Byte[] (Buffer Length = 256)
- byte[] bs3 = stream2.GetBuffer();
- // 6. Stream to Byte[]
- FileStream stream4 = new FileStream("a.dat", FileMode.Open, FileAccess.Read);
- stream4.Seek(0, SeekOrigin.Begin);
- byte[] bs4 = new byte[3];
- stream4.Read(bs4, 0, bs4.Length);
转自:http://hi.baidu.com/benbenzlj/item/3b429f72fe2560285d17896e