C#操作配置文件(增、删、改、查)

注意:操作App.config配置文件需要添加引用System.Configuration,并且在程序中using System.Configuration

1.判断键为create_man的项是否存在配置文件中

            //判断配置文件中是否存在键为create_man的项  
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == "create_man")
                {
                    Console.WriteLine("存在键为create_man的项");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("不存在键为create_man的项"");
                    Console.ReadLine();
                }
            }

2.读取配置文件,查询键为create_time的值

   //读取配置文件数据
            string ct = ConfigurationManager.AppSettings["create_time"];
             Console.WriteLine(ct);
              Console.ReadLine();

3.向配置文件中添加键为create_man值为tg的项

 //添加配置文件的项,键为creata_man,值为tg
            Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config1.AppSettings.Settings.Add("create_man", "tg");
            config1.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

4.删除键为create_man的项

            //删除配置文件键为create_man的项  
            Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config2.AppSettings.Settings.Remove("create_man");
            config2.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

5.修改配置文件中的键为create_time的值

            //修改配置文件数据
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["create_time"].Value = "2018-03-29 14:13:20";
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");






你可能感兴趣的:(c#)