Page 1 of 1

How to use the ConfigurationManager to save program-wide settings.

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1252
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 10 August 2010 - 05:54 PM

I’m currently creating an application that will let people easily upload their pictures to the popular image hosting site Imgur.

My end plan is to finish it (have it in a working state) and then release it on CodePlex. CodePlex is an open-source repository website by Microsoft where developers can share their code for free. If you’re familiar with Team Server, then using the website is very easy and can be integrated right into Visual Studio 2010.

Since my application revolves around an exposed API given to me by Imgur, if I’m to share this source code with the world, I shouldn’t give everyone access to my personal key.

One approach to solving this problem was to use the built-in ConfigurationManager.AppSettings.
Here’s how you do it (I’m using Windows Forms).

Right-click on your solution and click Add New Item:

Posted Image

Then select the AppSettings.config file:

Posted Image

Then, double click the created file, and you’ll see the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>


Application variables are saved in the appSettings node.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="API-Key" value="e0201e0b4528c146027c4f6dcd730787"/>
    <add key="WelcomeMessage" value="Hi there neighbor!"/>
    <add key="Error404" value="Welp, we couldn't find that!"/>
  </appSettings>
</configuration>


Now add a .dll reference in your project to System.Configuration, and also the using namespace to whatever class will be using the file.

So now that we have added a variable called API-Key, we can be access that anywhere/anytime with the ConfigurationManager class.

ConfigurationManager.AppSettings["API-Key"].ToString();


Unfortunately, the setting keys aren't strongly typed, but you could create a helper class for that easily. Have fun!

Is This A Good Question/Topic? 0
  • +

Page 1 of 1