How to get information from an App.config

Asked

Viewed 1,703 times

2

I’m doing a program where I want the user to put in the variable the number you need because it will vary from computer to computer what will be the number you need. I’m using App.config for that but it’s sending me the blank result of the condition I’m using in App.Config is this

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
    <add key ="teste" value="1234"/>
</appSettings>

The code I’m using to receive this value is this

string campoExtra = ConfigurationManager.AppSettings["teste"];
MessageBox.Show(campoExtra);

And Messagebox comes up blank I can’t find the error.

inserir a descrição da imagem aqui

  • The ConfigurationManager will try to capture the config information of the executable in question and not DLL’s.

2 answers

2


You need to open the configuration file first

ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

Assign the reading to a variable and make the readings from it

Configuration config= ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);


string campoExtra =  config.AppSettings.Settings[key].Value;
MessageBox.Show(campoExtra);

I have a class that assists me in this, if it is of your interest follows below:

public static class AppConfig
{
    private static Configuration config= ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);



    public static bool HasKey(string key)
    {
        return config.AppSettings.Settings.AllKeys.Contains(key);
    }
    public static string Get(string key)
    {
        return config.AppSettings.Settings[key].Value;
    }
    public static bool GetBolean(string key)
    {
        var value = config.AppSettings.Settings[key].Value;
        if (string.IsNullOrEmpty(value))
            return default(bool);
        return bool.Parse(value);
    }
    public static object GetObject(string key, Type type)
    {
        var method = type.GetMethod("Parse");
        if (method != null)
        {
            var v = method.Invoke(type, new[] { AppConfig.Get(key) });
            return v;
        }
        else
        {
            return AppConfig.Get(key);
        }

    }
    public static T Get<T>(string key)
    {
        var method = typeof(T).GetMethod("Parse", new[] { typeof(string) });
        if (method != null)
        {
            var v = method.Invoke(typeof(T), new[] { AppConfig.Get(key) });
            return (T)v;
        }
        throw new Exception("O tipo não é convertivel");

    }

    public static void SetValue(string key, object value)
    {


        if (value == null)
        {
            if (!HasKey(key))
                config.AppSettings.Settings.Add(key, "");
            else
                config.AppSettings.Settings[key].Value = "";

        }
        else
        {
            if (!HasKey(key))
                config.AppSettings.Settings.Add(key, value.ToString());
            else                   
                config.AppSettings.Settings[key].Value = value.ToString();
        }

        config.Save(ConfigurationSaveMode.Minimal);
    }
}

1

I created some settings in App.Config and search for information from it using your class and bringing to a textbox:

The configuration:

    ....
    </startup>
    <applicationSettings>
        <Consulta.Properties.Settings>
            <setting name="EnderecoBD" serializeAs="String">
                <value>local</value>
            </setting>
            <setting name="PortaBD” serializeAs=”String">
                <value>porta</value>
            </setting>
            <setting name="UsuarioBD" serializeAs="String">
                <value>usuario</value>
            </setting>
            <setting name="SenhaBD" serializeAs="String">
                <value>senha</value>
            </setting>
            <setting name="Banco" serializeAs="String">
                <value>banco</value>
            </setting>
            <setting name="CmdSQL" serializeAs="String">
                <value>comando</value>
            </setting>
        </Consulta.Properties.Settings>
    </applicationSettings>
</configuration>

And in class:

if (ComandoSQL.Text == String.Empty)    
{   
    string ComandoSQLRetorno = AppConfig.Get.(Key).CmdSQL.Value;
    ComandoSQL.Text = ComandoSQLRetorno;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.