views:

133

answers:

3

I am trying to use a config file in my C# console application. I created the file within the project by going New --> Application Configuration File, and naming it myProjectName.config. My config file looks like this:

<?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 looks like this:

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

Can anyone lend a hint as to why this is not working? (I am getting the error message.)

Thanks!!

badPanda

+1  A: 

check the documentation

http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx

Seattle Leonard
+2  A: 

First off, use ConfigurationManager instead of ConfigurationSettings.

Second, instead of saying "doesn't work", which provides no useful information, tell us what you're seeing. Does it compile? Does it throw an exception at runtime? Does your PC start to smoke and smell like melting plastic?

Try this:

    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;
    }
David Lively
I actually did say that it was throwing the error message in the if statement, but thank you for your answer.
badpanda
+3  A: 

You can't change the name from app.config and expect ConfigurationManager to find it without providing it more information. Change the name of myProjectName.config back to app.config, rebuild, and you will see a file in the bin folder called myProjectName.exe.config. Then your call will work ConfigurationManager.AppSettings should work correctly.

AJ