C#对配置文件的,增,删,改,查

时间:2022-05-20 20:16:06

对config进行增删改查操作需引用两个名称空间

using System.Configuration;
using System.Web.Configuration;

读操作(其中参数即config中的key值)

//(1)读
            string filepath = ConfigurationManager.AppSettings["FilePath"];
            return filepath;

增操作(第一个参数为key值,第二个参数为value)

//(2)添加
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
            AppSettingsSection app = config.AppSettings;
            app.Settings.Add("p", "p:\\");
            config.Save(ConfigurationSaveMode.Modified);

改操作(第一个参数为要修改的key值,第二个参数为修改后的value值)

//(3)修改
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
            AppSettingsSection app = config.AppSettings;
            app.Settings["p"].Value = @"g:\";
            config.Save(ConfigurationSaveMode.Modified);

删操作(节点的key值)

//(4)删除
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
            AppSettingsSection app = config.AppSettings;
            app.Settings.Remove("p");
            config.Save(ConfigurationSaveMode.Modified);