How to use application configuration file in C #?

I am trying to use a configuration file in my C # console application. I created the file inside the project by going to New β†’ Application Configuration File and naming it myProjectName.config. My configuration file is as follows:

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="SSDirectory" value="D:\Documents and Settings\****\MyDocuments\****" /> </appSettings> </configuration> 

The code to access it is as follows:

 private FileValidateUtil() { sSDirFilePath = ConfigurationSettings.AppSettings["SSDirectory"]; if (sSDirFilePath == null) Console.WriteLine("config file not reading in."); } 

Can someone tell me why this does not work? (I get an error.)

Thanks!!

badPanda

+7
c # file singleton configuration
source share
3 answers

You cannot change the name from app.config and wait for the ConfigurationManager to find it without giving it more information. Change the name myProjectName.config to app.config, rebuild, and you will see a file in the bin folder with the name myProjectName.exe.config. Then your call to ConfigurationManager.AppSettings should work correctly.

+8
source share
+2
source share

First of all, use ConfigurationManager instead of ConfigurationSettings .

Secondly, instead of saying β€œdoes not work,” which does not provide any useful information, tell us what you see. Will he compile? Does this throw an exception at runtime? Does your computer start to smoke and smell like melting plastic?

Try the following:

  public string GetSSDirectory() { string sSDirFilePath = string.Empty; if (!ConfigurationManager.AppSettings.AllKeys.Contains("SSDirectory")) { Console.WriteLine("AppSettings does not contain key \"SSDirectory\""); } else { sSDirFilePath = ConfigurationManager.AppSettings["SSDirectory"]; Console.WriteLine("AppSettings.SSDirectory = \"" + sSDirFilePath + "\""); } return sSDirFilePath; } 
+2
source share

All Articles