Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying app.config on fly

Seems a trivial question, but surprisingly, found only some solutions like this one, which explain how to add some properties, using deprecated functions. I'd rather want to edit one. So, how it's done in .NET 4.0?

To be more specific, need to set the location of database, in <connectionStrings> property.

like image 898
Arnthor Avatar asked Jul 21 '26 03:07

Arnthor


1 Answers

This code is adapted from this blog post and tested on .NET 4:

using System;
using System.Configuration;

class Program
{
    static void ShowConfig()
    {
        // For read access you do not need to call the OpenExeConfiguraton
        foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings)
        {
            Console.WriteLine("Key: {0}, Value: {1}", item.Name, item.ConnectionString);
        }
    }

    static void Main(string[] args)
    {
        ShowConfig();

        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        var conSettings = new ConnectionStringSettings("NewName", "New connstring value");
        config.ConnectionStrings.ConnectionStrings.Add(conSettings);
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("connectionStrings");

        Console.WriteLine("===UPDATE===");
        ShowConfig();

        Console.Read();
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="db1" connectionString="blah"/>
    </connectionStrings>
</configuration>

On my PC it prints

Key: LocalSqlServer, Value: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Key: db1, Value: blah
===UPDATE===
Key: LocalSqlServer, Value: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Key: db1, Value: blah
Key: NewName, Value: New connstring value  
like image 81
oleksii Avatar answered Jul 23 '26 15:07

oleksii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!