C# dictionary to bytes and bytes convert to dictionary

 static byte[] GetBytesFromDic(Dictionary<string,string> dic)
        {
            if(dic==null || !dic.Any())
            {
                return null;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                binFormatter.Serialize(ms, dic);
                byte[] dicBytes = ms.ToArray();           
                return dicBytes;
            }
        }

        static Dictionary<string,string> GetDicFromBytes(byte[] dicBytes)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            using (MemoryStream ms = new MemoryStream(dicBytes))
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                dic= (Dictionary<string,string>) binFormatter.Deserialize(ms);
            }
            return dic;
        }

MemoryStream ms=new MemoryStream(bytes);

ms.ToArray()

posted @ 2019-12-12 16:53  FredGrit  阅读(1173)  评论(0编辑  收藏  举报