我用下面的代码加密了app.config的userSettings节,程序在调试时没有问题,但是离开开发环境第一次运行时总是找不到加密提供者,而第二次运行时,就没有问题了,请高手帮忙 try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);                config.SectionGroups["userSettings"].Sections[0].SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");                config.AppSettings.SectionInformation.ForceSave = true;                config.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }//下面的代码是第一次运行总是出错的位置
private void btnCheckPwd_Click(object sender, EventArgs e)
        {
            if (txtPwd.Text == Properties.Settings.Default.Password)
            {
                MessageBox.Show("密码正确");
            }            MessageBox.Show(Properties.Settings.Default.Password);
        }

解决方案 »

  1.   

      Properties.Settings config = Properties.Settings.Default; 
       textBox1.Text = config.Password; 
       Properties.Settings config = Properties.Settings.Default; 
       config.Password= textBox2.Text; 
       config.Save(); 
    或用
    public static string GetConfigString(string key) 

    return ConfigurationSettings.AppSettings[key]; 
    } public static void SetValue(string AppKey,string AppValue) 

    XmlDocument xDoc = new XmlDocument();  
    xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); XmlNode xNode; 
    XmlElement xElem1; 
    XmlElement xElem2; 
    xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); 
    if ( xElem1 != null ) xElem1.SetAttribute("value",AppValue); 
    else 

    xElem2 = xDoc.CreateElement("add"); 
    xElem2.SetAttribute("key",AppKey); 
    xElem2.SetAttribute("value",AppValue); 
    xNode.AppendChild(xElem2); 

    xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config"); 
      

  2.   

     Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);应用程序配置信息 是在用户目录下 ,你离开开发环境后 配置信息不存在. 你应该加判断如果配置信息不存在使用默认配置信息.
      

  3.   


    根本就是瞎扯,我已经说过了,加密appSettings节和connectionString是没有问题的离开开发环境也只是第一次启动程序时有问题。第二次启动程序后就没有问题了