Good coding practice when saving data in .net files

To give a little background.

I created an application that allows users to save settings and then call the settings later. For this, I created some serializable objects. I got this to work using BinaryFormatter without much trouble.

When I start to encounter problems, I update the software and add new settings. Now my serializable objects do not match, and so I have to update the files. I have done this successfully for several versions. But for this, I try to deserialize the file, and if it throws an exception, I try to use the next version. And then the next. And then the next. Until I find the correct one. Then I have to write conversion functions for each of the old versions in order to convert it to the latest version. I also created a “revision” file, so I can just check which version they have and then update it, but I still need to save a lot of different “versions” and write conversion functions for all of them ,,which seems inherently messy for me and prone to bloat later on the line if I continue along this route.

There must be a better way to do this, I'm just not sure how to do this.

thank

+5
source share
6 answers

To enable assemblies, you need to write serialization bindings .

For settings, I use Dictionary<string, byte[]>to save to a file. I am serializing a dictionary, and all is well. When I add new settings, I provide a default setting if not found in the settings file.

In addition, if you add fields to a serialized object, you can decorate [Optional].

+3
source

XML . . XML, . "", Serialize/Deserialize, .

+1

, [DefaultValue()] - , XML. . xml , "", . System.ComponentModel :

class MySettings
{
    public int MaxNumLogins { get; set; }

    // specify the value to default to if it not present in the serialized file...
    [DefaultValue(0)]
    public int CacheTimeoutMinutes { get; set; }
}
0

, , ​​ .

0

You can take a look at ProtoBuf-Net http://code.google.com/p/protobuf-net/wiki/GettingStarted if you are making a binary because all of these things are related to version control, etc. also very compact. It is also actively developing, and if you potentially have cross-platform requirements, if you use the .proto file, you can also achieve this.

If you want people to be able to edit settings (outside of your program), you can use XML * serialization methods.

0
source

All Articles