开发者

Save and Load Dictionary from encrypted or unreadable or binary format?

I have a dictionary like the follow:

public Dictionary<int, SpawnList> spawnEntities = new Dictionary<int, SpawnList>();

The class being used is as follow:

    public class SpawnList
    {
        public int NpcID { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public int TitleID { get; set; }
        public int StaticID { get; set; }

        public entityType Status { get; set; }

        public int TypeA { get; set; }
        public int TypeB { get; set; }
        public int TypeC { get; set; }

        public int ZoneID { get; set; }
        public int Heading { get; set; }
        public float PosX { get; set; }
        public float PosY { get; set; }
        public float PosZ { get; set; }
   开发者_运维问答 }

/// <summary>Entity type enum.</summary>
public enum entityType
{
    Ally,
    Enemy,
    SummonPet,
    NPC,
    Object,
    Monster,
    Gatherable,
    Unknown
}
  • How could I save this Dictionary to either a binary or encrypted format so I could later Load it again into my application ?

    My biggest problem here is not on how to save the file it self or encrypt it but mostly on how to do it when you have a class with it and how you go about deserializing it later.

My limitation is .Net 3.5 can't use anything higher.


Separate the serialization aspect from the encryption aspect. There are various different ways of serializing the data:

  • Write your own serialization code
  • Use the built-in binary serializers
  • Use the built-in XML serializers
  • Use a 3rd party serialization framework such as Thrift or Protocol Buffers

All of these are likely to allow you to serialize and deserialize to/from a stream. Then you should look at using CryptoStream to handle the encryption/decryption - but be aware that if your own code needs to be able to decrypt the data with no extra information, then it will need to have the key available to it... which basically means it'll be available to anyone who is able to run the code, too.


Mark the class as

[Serializable]

and serialize it to any Stream using

FileStream stream = File.Create("binary.bin");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, spawnEntities);
stream.Flush();
stream.Close();

And Deserialize it using

stream = File.Open("binary.bin", FileMode.Open);
spawnEntities = formatter.Deserialize(stream) as Dictionary<int, SpawnList>;
stream.Close();


The easy way to get you started:

  1. Make your class serializable by attaching the [Serializable] attribute.
  2. Use CryptoStream and BinaryFormatter to serialize it into a file and encrypt the data.

The reference for CryptoStream provides a complete example for setting up encryption and doing the related file handling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜