Sometimes in the application there may be a configuration window to save the connection string to the app.config. Usually the windows application uses ApplicationName.exe.config to save the connection strings. Editing the app.config using the c# code may be eminent. The below code sample changes the connection string and saves it back to the application.exe.config file. But in my case the newly added string didn’t take effect unless I restart the application. The below code also demonstrates the encryption of app.config
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("windowsapp1.exe");
- if (config != null)
- {
- ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings");
- section.ConnectionStrings["NAME"].ConnectionString = "MY CON STRING HERE";
- if (section != null)
- {
- ////section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
- section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
- section.SectionInformation.ForceSave = true;
- }
- config.Save(ConfigurationSaveMode.Modified, true);
- ConfigurationManager.RefreshSection("connectionStrings");
- }
The above code uses the DataProtectionConfigurationProvider. You can also use RsaProtectedConfigurationProvider. But the config file cannot be copied to the other machine if RsaProtectedConfigurationProvider is used because it uses the machine code to encrypt which is unique to each computer.