Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypting connection string: "This operation does not apply at runtime"

Tags:

c#

I have a console application and it has app.config. When I run this code:

 class Program
    {
        static void Main()
        {

            ConnectionStringsSection connSection = ConfigurationManager.GetSection("connectionStrings") as 
                                                    ConnectionStringsSection;
            if (connSection != null)
            {
                if (!connSection.SectionInformation.IsProtected)
                    connSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

                else
                    connSection.SectionInformation.UnprotectSection();
            }

            Console.Read();
        }
    }

I get error: "This operation does not apply at runtime". I also tried giving permissions to my app.config but no luck.

What can the issue?

like image 783
Jaggu Avatar asked Dec 22 '22 07:12

Jaggu


2 Answers

You can try the following:

 static void Main()
 {


     // Get the current configuration file.
     System.Configuration.Configuration config =
             ConfigurationManager.OpenExeConfiguration(
             ConfigurationUserLevel.None);

     ConnectionStringsSection connSection = config.GetSection("connectionStrings") as
                                             ConnectionStringsSection;

     if (connSection != null)
     {
         if (!connSection.SectionInformation.IsProtected)
             connSection.SectionInformation.ProtectSection(null);

         else
             connSection.SectionInformation.UnprotectSection();
     }

     connSection.SectionInformation.ForceSave = true;

     config.Save(ConfigurationSaveMode.Full);

     Console.ReadKey();
 }
like image 96
Wouter de Kort Avatar answered Dec 23 '22 22:12

Wouter de Kort


I think you are supposed to use the OpenExeConfiguration method in this scenario:

  System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(pathToExecutable);

  ConnectionStringsSection connSection = 
    config .GetSection("connectionStrings") as ConnectionStringsSection;

the parameter pathToExecutable should be the full path to the exe of your application, for example: "C:\application\bin\myapp.exe"

like image 24
Edwin de Koning Avatar answered Dec 23 '22 20:12

Edwin de Koning