我有一个控制台应用程序,它有app.config。当我运行此代码时:
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();
}
}
我收到错误:“此操作在运行时不适用”。我也尝试过给我的app.config权限,但没有运气。
问题是什么?
答案 0 :(得分:5)
您可以尝试以下操作:
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();
}
答案 1 :(得分:4)
我认为你应该在这种情况下使用OpenExeConfiguration
方法:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(pathToExecutable);
ConnectionStringsSection connSection =
config .GetSection("connectionStrings") as ConnectionStringsSection;
参数pathToExecutable
应该是应用程序exe的完整路径,例如:“C:\ application \ bin \ myapp.exe”
答案 2 :(得分:2)
您不应该在运行时加密部分,使用aspnet_setreg.exe工具在运行时加密它们。 More info here.
ASP.NET然后在运行时透明地读取加密的部分。