ConfigurationManager, user settings and application settings

  • Thread starter Thread starter Mark Ingram
  • Start date Start date
M

Mark Ingram

Hi, I'm looking for a way to save 2 lots of information from my C#
application. I want to save information specific to the current user (such
as colour settings, non-essential data) and information specific to the
successful running of the application (such as server to connect to - but
only the administrator can update).

Can the ConfigurationManager class do this for me? If so, has anyone got any
example code of using it?

(The application settings should be saved in the same directory as the .exe
in case the application is installed on a network).

Thanks,

Mark
 
If the configuration data is per-user specific then saving it to the
same directory as the .exe file (even if installed on a network) is a
bad choise. User-specific data should be stored under the Documents and
Settings\[User]\Application Data folder, while application specific
data should be under the application's installation directory.

To answer your question yes ConfigurationManager (I am assuming this is
a .Net 2.0 question) can do this.
ConfigurationManager.OpenExeConfiguration method takes in a
ConfigurationUserLevel enum that specifies the whether to retrieve per
user configuration or per application. Below is the sample code:

Configuration config = ConfigurationManager.OpenExeConfiguration
(ConfigurationUserLevel.PerUserRoaming);
//use config to read / write configuration data

See
http://msdn2.microsoft.com/en-us/library/system.configuration.configurationuserlevel.aspx
for more information.

Hope this helps...

NuTcAsE
 
Yeah, i was hoping i would be able to just open up 2 lots of
ConfigurationManager instances, 1 to retrieve from Application Data folder
and one to retrieve from the .exe folder.

How do you handle the first run? Do you have to attempt to read the values,
if they dont exist write them out, or is there a system for setting default
values? (ie similar to using the registry, when retrieving keys there is the
option to specify a default value if the key was empty).

Thanks,
Mark
 
See inline...
How do you handle the first run? Do you have to attempt to read the values,
if they dont exist write them out, or is there a system for setting default
values? (ie similar to using the registry, when retrieving keys there is the
option to specify a default value if the key was empty).

If you are using custom configuration sections, then yes there is an
attribute you can apply to your properties / fields that contains the
default valules. So when you get the custom configuration section from
ConfigurationManager, it will contain its default values since the
section does not exist.

When applying a ConfigurationPropertyAttribute on a property of your
custom configuration you can supply a default value of that property.

Creating custom configurations :
http://msdn2.microsoft.com/library/ms228062.aspx
 
Back
Top