C# write value to config file and read from value, such as persistence

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections;

namespace ConsoleApp26
{
    internal class Program
    {
        static Dictionary<string, string> configDic = new Dictionary<string, string>();
        static void Main(string[] args)
        {
            InitConfigDic();
            FillConfigFile();
            ReadFromConfig();
            PrintConfigDic();
            Console.ReadLine();
        }

        private static void PrintConfigDic()
        {
            Console.WriteLine("In ConfigDic:");
            foreach(KeyValuePair<string,string> kvp in configDic)
            {
                Console.WriteLine($"Key:{kvp.Key},Value: {kvp.Value}");
            }
        }

        private static void ReadFromConfig()
        {
            Console.WriteLine("In ConfigurationManager.AppSettings:");
            foreach (KeyValuePair<string, string> kvp in configDic)
            {
                Console.WriteLine($"{kvp.Key},{ConfigurationManager.AppSettings[kvp.Key]}");
            }
        }

        private static void FillConfigFile()
        {
            foreach (KeyValuePair<string, string> kvp in configDic)
            {
                WriteToConfig(kvp.Key, kvp.Value);
            }
        }

        private static void InitConfigDic()
        {
            for (int i = 0; i < 10; i++)
            {
                configDic.Add($"Config{i + 1}", Guid.NewGuid().ToString());
            }
        }

        static void ListConfigurationFile()
        {
            var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Console.WriteLine($"ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) :" +
                $"{cfg.FilePath}");
            cfg = ConfigurationManager.OpenMachineConfiguration();
            Console.WriteLine($"ConfigurationManager.OpenMachineConfiguration():{cfg.FilePath}");
        }

        static void WriteToConfig(string cfgKey, string cfgValue)
        {
            var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            
            //Necessary,this will remove old value,and insert new value,else it will append new value after old value
            cfg.AppSettings.Settings.Remove(cfgKey);
            cfg.AppSettings.Settings.Add(cfgKey, cfgValue);
            cfg.Save(ConfigurationSaveMode.Full);
            ConfigurationManager.RefreshSection("appSettings");
        }

        static string ReadFromConfig(string cfgKey)
        {
            string cfgValue = null;
            cfgValue = ConfigurationManager.AppSettings[cfgKey];
            return cfgValue;
        }
    }
}

 

 

posted @ 2024-04-10 11:30  FredGrit  阅读(3)  评论(0编辑  收藏  举报