在app.config中有配置代码如下:
<configuration> <appSettings> <add key="ConStringEncrypt" value="false" /> <add key="ConnectionString" value="Server=localhost;Database=testmysql;User=root;Password=xiaowei;Port=3306;Charset=utf8" /> </appSettings> </configuration> |
在程序开始运行处加密数据库连接信息,防止别人盗用数据库密码信息
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { // 链接字符串加密 string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"]; string _connectionString = ConfigurationManager.AppSettings["ConnectionString"]; if (ConStringEncrypt == "false") { _connectionString = DESEncrypt.Encrypt(_connectionString); // 写入到config文件中 SetValue(Application.ExecutablePath + ".config", "ConStringEncrypt", "true"); SetValue(Application.ExecutablePath + ".config", "ConnectionString", _connectionString); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } public static void SetValue(string configPath, string AppKey, string AppValue) { XmlDocument xDoc = new XmlDocument(); //获取可执行文件的路径和名称 xDoc.Load(configPath); 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(configPath); } } |