Pergunta

I am trying to store a number of categories that will be used to populate a drop down list however I would like to have some base categories stored somewhere (been trying app.config) but then to also allow the user to add/remove categories as they require.

I've read a lot of information about the custom ConfigurationSection with a ConfigurationElementCollection but couldn't wrap my head around it. I ended up going with the delimited value option and using Split:

<appSettings>
    <add key="categories" value="Work;Education;Taxes;Medical"/>
</appSettings>

I then tried to do the following which I also found online:

string categories = ConfigurationManager.AppSettings.Get("categories");
ConfigurationManager.AppSettings.Remove("categories");
ConfigurationManager.AppSettings.Add("categories", categories + ";Test");

But get the error that it is Read Only.

My question is, what is the normal way to achieve something like this where a list of elements for a control like a combo box is stored in some config that can be read and modified?

Foi útil?

Solução

I think if you're using appSettings, it's perfectly fine, unless you expect the complexity or amount of data to get unwieldy. For a simple, small, mostly static lookup, I think it's ok.

As to your issue of not being able to save the values back to the config, you need to use ConfigurationManager.OpenExeConfiguration:

Configuration config =
    ConfigurationManager.OpenExeConfiguration("app.config");

string categories = ConfigurationManager.AppSettings.Get("categories");
config.AppSettings.Remove("categories");
config.AppSettings.Add("categories", categories + ";Test");

config.Save(ConfigurationSaveMode.Modified);

If you will have lots of complicated settings per user, then this approach isn't likely the best one. If a database isn't an option, you can just use a separate XML config file and load it / update it via XmlSerializer or XLinq.

Outras dicas

My question is, what is the normal way to achieve something like this where a list of elements for a control like a combo box is stored in some config that can be read and modified?

Why using the App.Config as a storage resource file?

You have so many other storage and persistence options, like:

simple text file, XML file, database and so on...

Just choose one.

As far as i know you won't be able to modify anything you hardcode into your project. Try to access and modify it from a file ( like a simple xml file ) or database.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top