52

I want to use App.config for storing some setting. I tried to use the next code for getting a parameter from a config file.

private string GetSettingValue(string paramName)
{
    return String.Format(ConfigurationManager.AppSettings[paramName]);
}

I also added System.Configuration for it (I used a separate class), and in App.config file I have:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key ="key1" value ="Sample" />
  </appSettings>
</configuration>

But I got an error while trying to use ConfigurationManager - ConfigurationManager can't exist in such context, but I already added System.Configuration. Or did I miss something?

EDIT:

class with config (full view)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace browser
{
    class ConfigFile
    {
        private string GetSettingValue(string paramName)
        {
            return String.Format(ConfigurationManager.AppSettings[paramName]);
        }
    }
}

EDIT2

Add how it looks

enter image description here

This means the problem is not during using ConfigurationManger but before - the program "says" that it "doesn't know such element" as I understand the error - the "Element ConfigurationManager" doesn't exist in such context"

EDIT3

enter image description here

EDIT 4

enter image description here

Pang
  • 9,564
  • 146
  • 81
  • 122
hbk
  • 10,908
  • 11
  • 91
  • 124
  • Did you add a `using System.Configuration` to the top of the `.cs` file? – Mike Perrenoud Oct 07 '13 at 19:14
  • yep - I'm write it "but I already add System.Configuration" – hbk Oct 07 '13 at 19:14
  • 3
    So that statement isn't really all that qualified. But you're stating that you added a **Reference** to `System.Configuration` **as well as** the `using System.Configuration` correct? – Mike Perrenoud Oct 07 '13 at 19:15
  • Is this dot after `string` a typo? – Jack Jul 26 '14 at 18:27
  • @Jack Where exactly you mean? – hbk Jul 26 '14 at 18:55
  • This part in your code: `String.` (note the `.`) in `GetSettingValue()` function. Is this C# valid syntax or a typo? – Jack Jul 26 '14 at 19:33
  • @Jack I think i miss `Format` method name in that code - now please see updated version. This was a typo - now must be OK. Alternative to `return String.Format(ConfigurationManager.AppSettings[paramName]);` you can try to use `return ConfigurationManager.AppSettings[paramName].ToString();`. If you are interest in this project - finished version you can find here - http://www.codeproject.com/Articles/660672/Sticky-notes-with-Csharp-Simple-application, with source code. Be hones, it's one of the first my program, when i just start to looking in to C#. – hbk Jul 27 '14 at 07:19
  • @Jack or you can just use `return ConfigurationManager.AppSettings[paramName];` without string – hbk Jul 27 '14 at 07:26
  • Possible duplicate of [How can I read/write app.config settings at runtime without using user settings?](https://stackoverflow.com/questions/3638754/how-can-i-read-write-app-config-settings-at-runtime-without-using-user-settings) – Matt Jun 22 '17 at 08:34

5 Answers5

41

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

bausa
  • 111
  • 2
  • 9
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
11

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
2

Using ASP .NET6

nstall NuGet package System.Configuration.ConfigurationManager

The name of my configuration file is App.Config

Content of App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="DBConnectionString" value="aa" />
        <add key="DBName" value="bb" />
        <add key="AuthKey" value="cc" />
    </appSettings>
</configuration>

File reading values, i.e. SettingsService.cs:

using namespc = System.Configuration;

namespace Ecommerce_server.Services.SetupOperation
{
    public interface ISettingsService
    {
        string MongoDBConnectionString { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

        string DataBaseName { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

        public string AuthKey { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

    }

    public class SettingsService : ISettingsService
    {
        public string MongoDBConnectionString { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

        public string DataBaseName { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

        public string AuthKey { get => namespc.ConfigurationManager.AppSettings["DBConnectionString"]!; }

    }
}

Note: We had to create a specialized namespace for ConfigurationManger to solve ambiguity.

Franco
  • 441
  • 3
  • 18
1

I found some answers, but I don't know if it is the right way. This is my solution for now. Fortunately it didn't break my design mode.

    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }
CJ Dennis
  • 4,226
  • 2
  • 40
  • 69
Mariano
  • 45
  • 4
  • 2
    Two users left negative ratings. It would be constructive to provide an indication why they consider the code is not good enough. I found out that if my application is located in C:\Program Files (x86)\MyApp, the code causes a crash, because the application does not have rights to save data in there. – Nick_F Jan 15 '18 at 03:24
  • 1
    The original user problem is not about creating a method to save a missing configuration, it's about being unable to retrieve it because of a missing import. That's why this question is probably being downvoted: it's misleading. – Giulio Caccin Oct 21 '19 at 15:22
  • This method works great, but there is a problem. It saves the setting in a '.config' file in XML format alongside the compiled executable. If you build an installer MSI and a local administrator installs the application, the config file ends in a sub-folder the c:\program files... folder. The end user has no access to write to this folder, so an error occurs on any attempt to modify the config in this situation. – tonyb Nov 10 '20 at 19:39
0

Add a reference to System.Configuration.dll by following these steps:

On the Project menu, select Add Reference.
In the Add Reference dialog box, select the .NET tab.
Find and select the Component Name of System.Configuration.
select OK.

This should add the ConfigurationManager

Store and retrieve custom information from an application configuration file

isubodh
  • 45
  • 7