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?
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();
}
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"
You are not supposed to encrypt sections at runtime, you encrypt them before runtime with the aspnet_setreg.exe tool. More info here.
ASP.NET then reads the encrypted sections at runtime transparently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.