stream byte

Stream & Byte[]

在涉及IO操作时,Stream 和 Byte[] 是最常用的,以下就做一个简单纪录。

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();
}

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);

在.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.如果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:
   直接使用内存流即可,代码如下:
MemoryStream ms = new  MemoryStream(bytes)

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using ProtoBuf;

namespace WindowsFormsApplication3
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
           List<User> list = new List<User>();
            for (int i = 0; i < 100; i++)
            {
                list.Add(new User() { UserID = i, UserName = "u" + i.ToString() });
            }

 

            MemoryStream stream2 = new MemoryStream();
            byte[] b =null;
            using (stream2) {

                Serializer.Serialize<List<User>>(stream2, list);
                b= stream2.GetBuffer();
                MessageBox.Show(b.Length.ToString());
            }

 

            MemoryStream ms = new MemoryStream(b);

            List<User> list3 = new List<User>();
            using(ms){


                list3 = Serializer.Deserialize<List<User>>(ms);
            }

            foreach (User u in list3)
            {
                Console.WriteLine(string.Format("UserID={0}, UserName={1}", u.UserID, u.UserName));
            }

 


            //protobuff
            string path = AppDomain.CurrentDomain.BaseDirectory + "protobuf.txt";
            using (Stream file = File.Create(path))
            {

               
                Serializer.Serialize<List<User>>(file, list);
               
              
              
                file.Close();
            }

            List<User> list2 = new List<User>();
            using (Stream file = File.OpenRead(path))
            {
                list2 = Serializer.Deserialize<List<User>>(file);
            }

            foreach (User u in list2)
            {
                Console.WriteLine(string.Format("UserID={0}, UserName={1}", u.UserID, u.UserName));
            }

          //  Console.ReadKey();
        }
    }

    [ProtoContract]
    public class User
    {
        [ProtoMember(1, IsRequired = true)]
        public int UserID { get; set; }

        [ProtoMember(2, IsRequired = true)]
        public string UserName { get; set; }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值