Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good coding practice when saving data to files in .net

Tags:

c#

.net

file-io

To give a bit of a background.

I have created an application that allows users to save settings and then recall the settings at a later date. To do this I have created some serializable objects. I have gotten this to work using the BinaryFormatter without much trouble.

Where I start to run into problems is when I upgrade 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 a few versions. But to do this I try deserializing the file and if it throws an exception, I try with the next version. . .and then the next. . .and then the next. . . until I find the right one. Then I have to write conversion functions for each of old versions to convert it into the newest version. I did create a "revision" file as well, so I can just check up front what version they have and then upgrade it, but I still have to keep a lot of different "versions" alive and write the conversion functions for all of them. . . which seems inherently messy to me and prone to bloat later on down the line if I keep going this route.

There has to be a better way to do this, I just am not sure how.

Thanks

like image 248
EatATaco Avatar asked Feb 19 '13 21:02

EatATaco


People also ask

How do I save a .NET code?

To save your work, click File > Save All. The files are then saved in the Document folder on your computer, inside of a folder called Visual Studio 2019 (or whatever version you have).


1 Answers

You need to write a serialization binder to resolve assemblies.

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

Also, if you are adding fields to a serialized object, you can decorate with [Optional].

like image 88
IAbstract Avatar answered Oct 03 '22 23:10

IAbstract