C# ConfigHelper 辅助类介绍

所属分类: 软件编程 / C#教程 阅读数: 65
收藏 0 赞 0 分享

复制代码 代码如下:

//==============================================
//        FileName: ConfigManager
//        Description: 静态方法业务类,用于对C#、ASP.NET中的WinForm & WebForm 项目程序配置文件
//             app.config和web.config的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作。

//==============================================
using System;
using System.Data;
using System.Configuration;
using System.Web;

using System.Collections.Generic;
using System.Text;
using System.Xml;

public enum ConfigurationFile
{
    AppConfig=1,
    WebConfig=2
}

/// <summary>
/// ConfigManager 应用程序配置文件管理器
/// </summary>
public class ConfigManager
{
    public ConfigManager()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }


    /// <summary>
    /// 对[appSettings]节点依据Key值读取到Value值,返回字符串
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">要读取的Key值</param>
    /// <returns>返回Value值的字符串</returns>
    public static string ReadValueByKey(ConfigurationFile configurationFile, string key)
    {
        string value = string.Empty;
        string filename = string.Empty;
        if (configurationFile.ToString()==ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点

        ////得到[appSettings]节点中关于Key的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

        if (element != null)
        {
            value = element.GetAttribute("value");
        }

        return value;
    }

    /// <summary>
    /// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">要读取的name值</param>
    /// <returns>返回connectionString值的字符串</returns>
    public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
    {
        string connectionString = string.Empty;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[appSettings]节点

        ////得到[connectionString]节点中关于name的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");

        if (element != null)
        {
            connectionString = element.GetAttribute("connectionString");
        }

        return connectionString;
    }

    /// <summary>
    /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">子节点Key值</param>
    /// <param name="value">子节点value值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点

        try
        {
            ////得到[appSettings]节点中关于Key的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

            if (element != null)
            {
                //存在则更新子节点Value
                element.SetAttribute("value", value);
            }
            else
            {
                //不存在则新增子节点
                XmlElement subElement = doc.CreateElement("add");
                subElement.SetAttribute("key", key);
                subElement.SetAttribute("value", value);
                node.AppendChild(subElement);
            }

            //保存至配置文件(方式一)
            using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
            {
                xmlwriter.Formatting = Formatting.Indented;
                doc.WriteTo(xmlwriter);
                xmlwriter.Flush();
            }

            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
            throw ex;
        }

        return isSuccess;
    }

    /// <summary>
    /// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">子节点name值</param>
    /// <param name="connectionString">子节点connectionString值</param>
    /// <param name="providerName">子节点providerName值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[connectionStrings]节点

        try
        {
            ////得到[connectionStrings]节点中关于Name的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");

            if (element != null)
            {
                //存在则更新子节点
                element.SetAttribute("connectionString", connectionString);
                element.SetAttribute("providerName", providerName);
            }
            else
            {
                //不存在则新增子节点
                XmlElement subElement = doc.CreateElement("add");
                subElement.SetAttribute("name", name);
                subElement.SetAttribute("connectionString", connectionString);
                subElement.SetAttribute("providerName", providerName);
                node.AppendChild(subElement);
            }

            //保存至配置文件(方式二)
            doc.Save(filename);

            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
            throw ex;
        }

        return isSuccess;
    }

    /// <summary>
    /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">要删除的子节点Key值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点

        ////得到[appSettings]节点中关于Key的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

        if (element != null)
        {
            //存在则删除子节点
            element.ParentNode.RemoveChild(element);
        }
        else
        {
            //不存在
        }

        try
        {
            //保存至配置文件(方式一)
            using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
            {
                xmlwriter.Formatting = Formatting.Indented;
                doc.WriteTo(xmlwriter);
                xmlwriter.Flush();
            }

            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
        }

        return isSuccess;
    }

    /// <summary>
    /// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">要删除的子节点name值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool DeleteByName(ConfigurationFile configurationFile, string name)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件

        XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[connectionStrings]节点

        ////得到[connectionStrings]节点中关于Name的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");

        if (element != null)
        {
            //存在则删除子节点
            node.RemoveChild(element);
        }
        else
        {
            //不存在
        }

        try
        {
            //保存至配置文件(方式二)
            doc.Save(filename);

            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
        }

        return isSuccess;
    }

}

更多精彩内容其他人还在看

WPF仿三星手机充电界面实现代码

这篇文章主要为大家详细介绍了WPF仿三星手机充电界面实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

浅谈C#各种数组直接的数据复制/转换

下面小编就为大家带来一篇浅谈C#各种数组直接的数据复制/转换。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

C#访问SQLServer增删改查代码实例

这篇文章主要为大家详细介绍了C#访问SQLServer增删改查代码实例,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C#根据身份证号码判断出生日期和性别

这篇文章主要为大家详细介绍了C#根据身份证号码判断出生日期和性别的方法,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C# 向Word中设置/更改文本方向的方法(两种)

在一般情况下word中输入的文字都是横向的,今天小编给大家带来两种方法来设置更改文本方向的方法,非常不错,对c# word 更改文本方向的知识感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

让C# Excel导入导出 支持不同版本Office

让C# Excel导入导出,支持不同版本的Office,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C#设置自定义文件图标实现双击启动(修改注册表)

这篇文章介绍的是利用C#设置自定义文件图标,然后实现双击启动的功能,文章给出了示例代码,介绍的很详细,有需要的可以参考借鉴。
收藏 0 赞 0 分享

C#两个相同属性的类赋值方法

这篇文章主要介绍了C#两个相同属性的类赋值方法的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

C#中ListView控件实现窗体代码

这篇文章主要介绍了C#中ListView控件实现窗体的核心代码,非常不错,具有参考借鉴价值,对c#listview相关知识感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

浅谈C# 序列化与反序列化几种格式的转换

下面小编就为大家带来一篇浅谈C# 序列化与反序列化几种格式的转换。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多