Encrypting app.exe.config using C# code (Or) Modify app.config at runtime

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


Code Snippet
  1. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("windowsapp1.exe");
  2.             if (config != null)
  3.             {
  4.                 ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings");
  5.                 section.ConnectionStrings["NAME"].ConnectionString = "MY CON STRING HERE";
  6.                 if (section != null)
  7.                 {
  8.                     ////section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
  9.                     section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
  10.                     section.SectionInformation.ForceSave = true;
  11.                 }
  13.                 config.Save(ConfigurationSaveMode.Modified, true);
  14.                 ConfigurationManager.RefreshSection("connectionStrings");
  15.             }


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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s