C# object to string and back

前端 未结 3 2020
梦毁少年i
梦毁少年i 2021-02-05 16:13

My problem:
I have a dynamic codecompiler which can compile a snippet of code. The rest of the code. (imports, namespace, class, main function) is already there. The snipp

3条回答
  •  广开言路
    2021-02-05 17:07

    Serialize the object using the BinaryFormatter, and then return the bytes as a string (Base64 encoded). Doing it backwards gives you your object back.

    public string ObjectToString(object obj)
    {
       using (MemoryStream ms = new MemoryStream())
       {
         new BinaryFormatter().Serialize(ms, obj);         
         return Convert.ToBase64String(ms.ToArray());
       }
    }
    
    public object StringToObject(string base64String)
    {    
       byte[] bytes = Convert.FromBase64String(base64String);
       using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
       {
          ms.Write(bytes, 0, bytes.Length);
          ms.Position = 0;
          return new BinaryFormatter().Deserialize(ms);
       }
    }
    

提交回复
热议问题