Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
I am using the below code to add a new connection string in my app.config file but it is not updating nor it is throwing any error.
When i execute this code the message box displaysonly the firs two connection strings and app.config file is also not updated

C#
try
            {
                
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                //ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
                //ConfigurationPermission cp = new ConfigurationPermission(System.Security.Permissions.PermissionState.Unrestricted);
                ConnectionStringSettings css = new ConnectionStringSettings("cString3", "abcdefxyz");
                config.ConnectionStrings.ConnectionStrings.Add(css);
                config.Save(ConfigurationSaveMode.Minimal);
                ConfigurationManager.RefreshSection("connectionStrings");
                foreach (ConnectionStringSettings connection in connections)
                {
                    string str = connection.Name;
                    string val = connection.ConnectionString;
                    MessageBox.Show(str + " " + val);
                    //textBox1.Text = str;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


and my xml file is

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Setting1" value="1" />
    <add key="Setting2" value="2" />
  </appSettings>
  <connectionStrings>
    <add name="cString1" connectionString="The first connection string is correct"/>
    <add name="cString2" connectionString="The second connection string"/>
  </connectionStrings>
</configuration>
Posted

Have a look at Read/Write App.Config File with .NET 2.0[^]

Best regards
Espen Harlinn
 
Share this answer
 
Comments
nishanjain 4-Sep-12 8:41am    
it doesnt work
Espen Harlinn 4-Sep-12 8:45am    
It will not modify app.config because app.config gets copied to bin\release\{executable}.config or bin\debug\{executable}.config depending on release or debug build, and that's the file that gets modified.

nishanjain 4-Sep-12 9:03am    
Is their any method to save app.config file as i want to add connection string in app.config
Espen Harlinn 4-Sep-12 9:05am    
Look for 'How To Read/Write Another App.Config File' in the article
 
Share this answer
 
Comments
nishanjain 4-Sep-12 8:58am    
its making the changes but its not able to save the changes
Santhosh Kumar Jayaraman 4-Sep-12 9:00am    
yes these changes are applicable for runtime only i.e. only for that instance.
Santhosh Kumar Jayaraman 4-Sep-12 9:02am    
You need to look at my another article, to know how to write changes in xml. Here i am saving the value from gridview to xml..You have to make necessary cahnges to populate it from your textbox or any other control

http://www.codeproject.com/Tips/426762/XML-to-DataSet-or-GridView-and-back
nishanjain 4-Sep-12 9:02am    
then what to do if i want these changes to be permanent
Vani Kulkarni 4-Sep-12 9:11am    
if you want the changes to be permanent, why dont you write it in app.config yourself. Why go through code?
C#
try
            {
                
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                //ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
                //ConfigurationPermission cp = new ConfigurationPermission(System.Security.Permissions.PermissionState.Unrestricted);
                ConnectionStringSettings css = new ConnectionStringSettings("cString3", "abcdefxyz");
                config.ConnectionStrings.ConnectionStrings.Add(css);
                config.Save();
                ConfigurationManager.RefreshSection("connectionStrings"); //May be this is unnecessary.
                foreach (ConnectionStringSettings connection in connections)
                {
                    string str = connection.Name;
                    string val = connection.ConnectionString;
                    MessageBox.Show(str + " " + val);
                    //textBox1.Text = str;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


So, I have implemented this on one of my projects (Enterprise Library 4.1):
C#
private static void CopyCurrentDataConfiguration(IDataConfiguration dataConfig)
       {
           // Load the configuration from the configuration file
           var configSource = ConfigurationSourceFactory.Create();

           // Retrieve the default datasource name
           var dataConfigurationSection = (DatabaseSettings)configSource.GetSection(
               DatabaseSettings.SectionName);
           var defaultDatabaseName = dataConfigurationSection.DefaultDatabase;

           CopyConnectionStrings(dataConfig, defaultDatabaseName);
       }

       private static void CopyConnectionStrings(IDataConfiguration dataConfig,string defaultDatabaseName)
       {
           // Add the configurations from our application config file to the builder
           foreach (ConnectionStringSettings settings in ConfigurationManager.ConnectionStrings)
           {
               try
               {
                   var configuredDatabase = dataConfig
                     .ForDatabaseNamed(settings.Name)
                     .ThatIs
                     .AnotherDatabaseType(settings.ProviderName);

                   if (settings.Name.Equals(defaultDatabaseName))
                   {
                       configuredDatabase.AsDefault();
                   }
               }
               catch { }
           }
       }

       public static void AddNewConnectionString(string databaseName, string connString)
       {
           var builder = new ConfigurationSourceBuilder();
           var dataConfig = builder.ConfigureData();
           CopyCurrentDataConfiguration(dataConfig);

           // Add our database connections to the builder
           dataConfig
             .ForDatabaseNamed(databaseName)
             .ThatIs
             .AnotherDatabaseType("Oracle.DataAccess.Client")
             .WithConnectionString(connString)
             .AsDefault();

           string conn = "your_connection_string";

           // Create a new configuration source, update it with the builder and make it the current configuration
           var newConfigSource = new DictionaryConfigurationSource();
           builder.UpdateConfigurationWithReplace(newConfigSource);
           EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(newConfigSource);
       }


Hope it helps.
 
Share this answer
 
v2
Comments
nishanjain 4-Sep-12 8:41am    
ConfigurationManager.RefreshSection("connectionStrings");
removing the line doesnt work
Christian Amado 4-Sep-12 8:42am    
Remove this ConfigurationSaveMode.Minimal. I have something similar developed with Enterprise Library and working.
Christian Amado 4-Sep-12 9:01am    
Improved solution for you :)
Hi,


This might not be the actual solution.But try saving it as

ConfigurationSaveMode.Modified instead of ConfigurationSaveMode.Minimal


Hope this helps.
 
Share this answer
 
Comments
nishanjain 4-Sep-12 8:43am    
i tried even this but its not working:(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900