Home > Article > Backend Development > asp.net reads and modifies config file implementation code
Add the app.config file to the project:
Right-click the project name, select "Add" → "Add New Item", in the "Add New Item" dialog box that appears, select "Add Application Configuration File"; if If the project does not have a configuration file before, the default file name is "app.config". Click "OK". The app.config file that appears in the designer view is:
b7fb1c986616c7c40c0535ea39670d25
f9d9f4a8f32d97f3ef0c10742ed31240
4b1b9d85fe86862ae3eab7e2045cf8a0
After the project is compiled, Under the binDebuge file, two configuration files will appear (taking this project as an example), one named "JxcManagement.EXE.config" and the other named "JxcManagement.vshost.exe.config". The first file is the configuration file actually used by the project, and changes made during the running of the program will be saved here; the second file is the synchronization file of the original code "app.config", which will not occur while the program is running. Change.
2. connectionStrings configuration section:
Please note: If your SQL version is 2005 Express version, the SQL server instance name is localhostSQLExpress during default installation. You must change the sentence "Data Source=localhost;" in the following example to "Data Source= localhostSQLExpress;", do not add spaces on both sides of the equal sign.
087f2e7731ad436bf1d04988350af758
<connectionStrings> <clear /> <addname="conJxcBook" connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********" providerName="System.Data.SqlClient" /> </connectionStrings>
appSettings configuration section:
appSettings configuration section is the configuration of the entire program. If it is the configuration of the current user, please use the userSettings configuration section. Its format is written with the following configuration The requirements are the same.
5e87e6047d0dec6f6908662b64721de4
<appSettings> <clear /> <addkey="userName"value="" /> <addkey="password"value="" /> <addkey="Department"value="" /> <addkey="returnValue"value="" /> <addkey="pwdPattern"value="" /> <addkey="userPattern"value="" /> </appSettings>
4. Reading and updating app.config
For reading and writing the app.config file, refer to the online article: http:// www.codeproject.com/csharp/ SystemConfiguration.asp is titled "Read/Write App.Config File with .NET 2.0".
Please note: To use the following code to access the app.config file, in addition to adding a reference to System.Configuration, you must also add a reference to System.Configuration.dll in the project.
4.1 Read the connectionStrings configuration section
///<summary> ///依据连接串名字connectionName返回数据连接字符串 ///</summary> ///<param name="connectionName"></param> ///<returns></returns> private static string GetConnectionStringsConfig(string connectionName) { string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString(); Console.WriteLine(connectionString); return connectionString; }
4.2 Update the connectionStrings configuration section
///<summary> ///更新连接字符串 ///</summary> ///<param name="newName">连接字符串名称</param> ///<param name="newConString">连接字符串内容</param> ///<param name="newProviderName">数据提供程序名称</param> private static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName) { bool isModified = false; //记录该连接串是否已经存在 //如果要更改的连接串已经存在 if (ConfigurationManager.ConnectionStrings[newName] != null) { isModified = true; } //新建一个连接字符串实例 ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName); // 打开可执行的配置文件*.exe.config Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // 如果连接串已存在,首先删除它 if (isModified) { config.ConnectionStrings.ConnectionStrings.Remove(newName); } // 将新的连接串添加到配置文件中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); // 保存对配置文件所作的更改 config.Save(ConfigurationSaveMode.Modified); // 强制重新载入配置文件的ConnectionStrings配置节 ConfigurationManager.RefreshSection("ConnectionStrings"); }
4.3 Read the appStrings configuration section
///<summary> ///返回*.exe.config文件中appSettings配置节的value项 ///</summary> ///<param name="strKey"></param> ///<returns></returns> private static string GetAppConfig(string strKey) { foreach (string key in ConfigurationManager.AppSettings) { if (key == strKey) { return ConfigurationManager.AppSettings[strKey]; } } return null; }
4.4 Update the connectionStrings configuration section
///<summary> ///在*.exe.config文件中appSettings配置节增加一对键、值对 ///</summary> ///<param name="newKey"></param> ///<param name="newValue"></param> private static void UpdateAppConfig(string newKey, string newValue) { bool isModified = false; foreach (string key in ConfigurationManager.AppSettings) { if(key==newKey) { isModified = true; } } // Open App.Config of executable Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // You need to remove the old settings object before you can replace it if (isModified) { config.AppSettings.Settings.Remove(newKey); } // Add an Application Setting. config.AppSettings.Settings.Add(newKey,newValue); // Save the changes in App.config file. config.Save(ConfigurationSaveMode.Modified); // Force a reload of a changed section. ConfigurationManager.RefreshSection("appSettings"); }
/// <summary> /// 写入Key,Value 到XML文件 /// </summary> /// <param name="Key"></param> /// <param name="Value"></param> public static void SaveConfig(string Key,string Value) { XmlDocument doc = new XmlDocument(); //获得配置文件的全路径 string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "App.config"; doc.Load(strFileName); //找出名称为“add”的所有元素 XmlNodeList nodes = doc.GetElementsByTagName("add"); for (int i = 0; i < nodes.Count; i++) { //获得将当前元素的key属性 XmlAttribute att = nodes[i].Attributes["key"]; //根据元素的第一个属性来判断当前的元素是不是目标元素 if (att.Value == Key) { //对目标元素中的第二个属性赋值 att = nodes[i].Attributes["value"]; att.Value = Value; break; } } //保存上面的修改 doc.Save(strFileName); }
More asp.net Read and modify config file implementation For code-related articles, please pay attention to the PHP Chinese website!