设置或读取config文件(winform)

using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;

/// <summary>
///SetConfi 的摘要说明
/// </summary>
public sealed class SetConfig
{
    public SetConfig()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 得到配置文件中的配置string信息
    /// </summary>
    /// <param name="SectionName">如果节点为null或者"",则默认获取appSettings节点</param>
    /// <param name="key">键</param>
    /// <returns></returns>
    public static string GetConfigString(string SectionName, string key)
    {
        if (SectionName == null || SectionName == "")
        {
            NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
            if (cfgName[key] == null || cfgName[key] == "")
            {
                throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
            }
            else
            {
                return cfgName[key];
            }
        }
        else
        {
            NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig(SectionName);
            if (cfgName[key] == null || cfgName[key] == "")
            {
                throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
            }
            else
            {
                return cfgName[key];
            }
        }
    }

    /// <summary>
    /// 得到配置文件中的配置decimal信息
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static decimal GetConfigDecimal(string SectionName, string key)
    {
        decimal result = 0;
        string cfgVal = GetConfigString(SectionName, key);
        if (null != cfgVal && string.Empty != cfgVal)
            result = decimal.Parse(cfgVal);

        return result;
    }
    /// <summary>
    /// 得到配置文件中的配置int信息
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static int GetConfigInt(string SectionName, string key)
    {
        int result = 0;
        string cfgVal = GetConfigString(SectionName, key);
        if (null != cfgVal && string.Empty != cfgVal)
            result = Int32.Parse(cfgVal);

        return result;
    }   

    /// <summary>
    /// 写入配置文件
    /// </summary>
    /// <param name="SectionName">节点名称</param>
    /// <parma name="key">键名</param>
    /// <parma name="value">键值</param>F:\至盈电子\PrintStock\PrintStock\PrintStock\Login.cs
    public static void SetConfigKeyValue(string SectionName, string key, string value)
    {
        //导入配置文件
        XmlDocument doc = loadConfigDocument();
        //重新取得 节点名
        XmlNode node = doc.SelectSingleNode("//" + SectionName);
        if (node == null)
            throw new InvalidOperationException(SectionName + " section not found in config file.");

        try
        {
            // 用 'add'元件 格式化是否包含键名 
            // select the 'add' element that contains the key
            XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

            if (elem != null)
            {
                //修改或添加键值
                elem.SetAttribute("value", value);
            }
            else
            {
                //如果没有发现键名则进行添加设置键名和键值
                elem = doc.CreateElement("add");
                elem.SetAttribute("key", key);
                elem.SetAttribute("value", value);
                node.AppendChild(elem);
            }
            doc.Save(getConfigFilePath());
        }
        catch
        {
            throw;
        }

    }

    /// <summary>
    /// 移除节点
    /// </summary>
    /// <param name="SectionName">节点名称</param>
    /// <param name="key">键</param>
    public static void RemoveSectionKey(string SectionName, string key)
    {
        //导入配置文件
        XmlDocument doc = loadConfigDocument();

        //重新取得 节点名
        XmlNode node = doc.SelectSingleNode("//" + SectionName);

        try
        {
            if (node == null)
                throw new InvalidOperationException(SectionName + " section not found in config file.");
            else
            {
                // 用 'add' 方法格式 key和value
                node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
                doc.Save(getConfigFilePath());
            }
        }
        catch (NullReferenceException e)
        {
            throw new Exception(string.Format("The key {0} does not exist.", key), e);
        }
    }

    /// <summary>
    /// 读入配置文件
    /// </summary>
    private static XmlDocument loadConfigDocument()
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(getConfigFilePath());
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

    /// <summary>
    /// 取得置文件路径和名称
    /// </summary>
    private static string getConfigFilePath()
    {
        return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
    }
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值