Is there a better way to store a list of strings in an applications config file than using a StringCollection?

Refresh

December 2018

Views

1.9k time

2

I have a list of filenames I need to store in my applications config file.

The only collection that comes up in the initial combo box on the settings page is System.Collections.Specialized.StringCollection. Now initially I didn't query this as I converted this to a List<string> straight away. There was one piece of code I wasn't happy with which was the copying of this list to and from the ListBox on the configuration dialog:

public List<string> ImageNames
{
    get
    {
        return folderImages.Items.ToList();
    }
    set
    {
        folderImages.Items.AddRange(value.ToArray());
    }
}

However, I've been revisiting my code and thought that if I kept the list as a StringCollection I could improve this code. Everywhere else I used the list/collection was OK, but this conversion still isn't to my liking:

public StringCollection ImageNames
{
    get
    {
        var names = new StringCollection();
        names.AddRange(folderImages.Items.ToList().ToArray());
        return names;
    }
    set
    {
        value.ToList().ForEach(imageName => folderImages.Items.Add(imageName));
    }
}

Actually, now I see the code side-by-side (as it were) I'm thinking that the List<string> version is "cleaner" - it's certainly clearer.

So is there another collection or list type I can store in the settings file? I'd really like to avoid the conversion on reading and writing the settings file if at all possible.

Failing that - is there a cleaner way of converting between a StringCollection and an ListBox.ObjectCollection (the ListBox.Items)?

2 answers

0

В конце концов , я на самом деле вернулся к моему первоначальному коду, но с гораздо более чистыми переходами между StringCollectionи List<string>- уродство , который была моя отправная точка.

Так что теперь при запуске у меня есть:

possibleImageNames = Properties.Settings.Default.Images.ToList();

и закрыть (где я обновить конфигурационный файл) у меня есть:

Properties.Settings.Default.Images.Clear();
Properties.Settings.Default.Images.AddRange(possibleImageNames.ToArray());

Если ToListметод на StringCollectionэто метод расширения - используется для инкапсуляции зацикливания кода.

1

Вы можете сохранить System.Object в настройках приложения, его не в исходном поле со списком, но оно есть, то вы можете просто хранить данные непосредственно от объекта.