Settings File and Compatibility

Started by
1 comment, last by Drakken255 11 years, 6 months ago
Hello all,

Bear in mind this is a bit difficult for me to explain.
I currently have a set of check boxes in my settings form and I might add more in later updates. I want to save these to a file in the general format of:

false
true
false
etc etc...

But what happens when an update adds a check box or two? I try to load the file's boolean values into them with:


string [] array = File.ReadAllLines(<FILE>);

checkboxOne.Checked = bool.Parse(array[0])
checkboxTwo.Checked = bool.Parse(array[1])
//etc etc...


But when it gets to the new check boxes, for which there is no line in the file, it will throw an IndexOutOfBoundsException because the file has x minus number-of-boxes-added lines and thus so does the array. Example:
5 old boxes, 3 new. the file and array count 5, so when the program reaches index 5 (the sixth and nonexistent line), exception.

Is there a better way to implement this to allow for a growing set of check boxes? Should I constantly check if the array length is less and resize as necessary?
Advertisement
There are really two major options:

The first is to stick with your serialized format, just adding a version number. When settings change you increase the version number. If you load old settings you either ignore the old settings or migrate them to the new settings.

The second major option is to serialize both the variable and the data. There have been many major formats over the years, such as .ini and xml, that allow you to save things in name/value pairs. If something is missing you can use some default settings, and extra values don't need to be loaded.

Both methods have benefits and drawbacks.
So the following should work:


int oldLength = settings.Length;
if (settings.Length < numberOfBoxes)
{
Array.Resize(ref settings, numberOfBoxes);

for (int i = oldLength; i < settings.Length; i++)
{
settings = "false";
}
}


And then each time settings change I just modify the constant numberOfBoxes?
As it is I'm not yet comfortable with XML serialization. I currently use manual data storage with File.WriteAllLines(). I'm assuming it's a much better way to go in this situation?

EDIT: I seem to have found a solution involving a Checked List Box. I didn't want to make a separate file out of it, but oh well. When saving, I save with:


List<string> checkedItems = new List<string>();

foreach (object checkedBox in checkBoxList.CheckedItems)
{
checkedItems.Add(checkedBox.ToString());
}

File.WriteAllLines(<FILE>, checkedItems.ToArray<string>());


And Load with:


List<string> checkedItems = new List<string>();
checkedItems.AddRange(File.ReadAllLines(<FILE>));

for (int i = 0; i < checkBoxList.Items.Count; i++)
{
if (checkedItems.Contains(checkBoxList.Items.ToString())
{
checkBoxList.SetItemChecked(i, true);
}
}

This topic is closed to new replies.

Advertisement