0

Goal

  • Save current the dynamic object to file
  • Load the save and set it

I search and found the below method. but it's for serializable field/class.

For Serializable

public byte[] ToByteArray<T>(T obj)
{
   BinaryFormatter b = new BinaryFormatter()
   using(MemoryStream m = new MemoryStream)
   {
      b.Serialize(m,obj);
      return ms.ToArray();
   }
}

public T FromByteArray<T>(byte[] data)
{
   BinaryFormatter b = new BinaryFormatter()
   using(MemoryStream m = new MemoryStream)
   {
      object obj = b.Deserialize(m);
      return (T)obj;
   }
}

Goal Example

The dynamic d can't be a serializable class because it hasn't only x,y and z. My goal is creating two functions: Save a list of dynamic to file and Load it from file.

  • bool ToFile(List list, string where)
  • List Load(string where)
List<dynamic> save = new List<dynamic>();

dynamic d = new ExpandoObject();

d.x = 1;
d.y = 3;

save.add(d);

d.z = 5;
d._type = "1";

save.add(d);

ToFile(save,"C:/Save.byte");

List<dynamic> load = Load("C:/Save.byte");

for(int I = 0; I < load.Count; I++)
{
   print("Round " + I);
   if(load[I].z != null)
      print(load[I].z);
}

Console

Round 1
Round 2
5
Chat Dp
  • 555
  • 5
  • 15

1 Answers1

3

I know this is not what you expected from the algorithm point of view, but the following solution reaches the declared goal. First of all, in your example, both items on your list are the same item. I changed the main code to this:

var bs = new BinaryStorage();
List<dynamic> save = new List<dynamic>();

dynamic d = new ExpandoObject();
d.x = 1;
d.y = 3;
d.name = "You can also add text of any length here";
save.Add(d);

dynamic e = new ExpandoObject();
e.z = 5;
e._type = "1";
save.Add(e);

bs.writeToFile(save, "data.bin");

List<dynamic> load = bs.readFromFile("data.bin");
int i = 0;
foreach (var item in load)
{
  i++;
  Console.WriteLine(item.z == null ? $"{i}: (null)" : $"{i}: {item.z}");
}

The BinaryStorage class looks like this:

public class BinaryStorage
{
  // add methods CopyTo, Zip, and Unzip

  public void writeToFile(List<dynamic> data, string fname)
  {
    string jtext = JsonConvert.SerializeObject(data, Formatting.None);
    File.WriteAllBytes(fname, Zip(jtext));
  }

  public List<dynamic> readFromFile(string fname)
  {
    var bin = File.ReadAllBytes(fname);
    var res = JsonConvert.DeserializeObject<List<dynamic>>(Unzip(bin));
    return res;
  }
}

This example produces data.bin file of 99 bytes. The other three methods of the class you can take from this answer:

Compression/Decompression string with C#

skch
  • 46
  • 2