wpf config配置文件的修改

该类 实现了 自动创建 一个 APP.CONFIG 功能

注意  因为使用了  Configuration  所以需要在项目里面添加

///

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.IO;

namespace mySerialPort.Com
{
    public static class MyConfig
    {

         public static void ConfigInit()
        {
           string  Filename =System.Environment.CurrentDirectory + "\\app.config";
           if (File.Exists(Filename) != true)
           {
               SetVaule("ServerIp", "192.168.1.126");   // 包含了 自动创建 的功能
               SetVaule("ServerPort", "1261");
           }
        }

        ///<summary>
        ///返回*.exe.config文件中appSettings配置节的value项 
        ///</summary>
        ///<param name="strKey"></param>
        ///<returns></returns>
        public static string GetVaule(string strKey)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap();
            file.ExeConfigFilename = "app.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

        ///<summary> 
        ///在*.exe.config文件中appSettings配置节增加一对键值对 
        ///</summary> 
        ///<param name="newKey"></param> 
        ///<param name="newValue"></param> 
        public static void SetVaule(string newKey, string newValue)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap();
            file.ExeConfigFilename = "app.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        public static void testc()
        {
            MyConfig.SetVaule("path", "");
         //  cancle.WriteLine(MyConfig.GetVaule("path"));
        }

    }
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值