using System;

using System.Collections.Generic;

using System.Configuration;

using System.IO;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Threading.Tasks;

using System.Xml;





namespace HandPickCrawlerDB.Extensions

{

    public class AppHelper

    {

        private static string _appconfig = null;





        public static string AppConfig

        {

            get

            {

                if (_appconfig == null)

                {

                    Type t = typeof(System.Configuration.ConfigurationManager).Assembly.GetType("System.Configuration.ClientConfigurationHost");

                    object cfghst = Activator.CreateInstance(t, true);

                    PropertyInfo pi = t.GetProperty("ConfigPaths", BindingFlags.Instance | BindingFlags.NonPublic);

                    object cfgpath = pi.GetValue(cfghst, null);





                    Type t1 = typeof(System.Configuration.ConfigurationManager).Assembly.GetType("System.Configuration.ClientConfigPaths");

                    pi = t1.GetProperty("ApplicationConfigUri", BindingFlags.Instance | BindingFlags.NonPublic);

                    string path = (string)pi.GetValue(cfgpath, null);





                    if (string.IsNullOrEmpty(path))

                        _appconfig = string.Empty;

                    else

                        _appconfig = path.Replace(".vshost.", ".");

                }

                return _appconfig;

            }

            set

            {

                _appconfig = value;

            }

        }





        public static void SetSettingToAppConfig(string key, string value)

        {

            if (string.IsNullOrEmpty(key))

            {

                throw new Exception("key not be null");

            }

            else

            {

                key = key.Trim();

            }

            if (string.IsNullOrEmpty(value))

                value = "";

            else

                value = value.Trim();





            if (!File.Exists(AppConfig))

            {

                throw new DirectoryNotFoundException();

            }

            File.SetAttributes(AppConfig, FileAttributes.Normal);

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(AppConfig);

            XmlNodeList xmllst = xmldoc.SelectNodes("/configuration/appSettings/add");

            if (xmldoc.SelectSingleNode("/configuration/appSettings") == null)

            {

                XmlNode n2 = xmldoc.CreateNode("element", "appSettings", "");

                n2.InnerXml = "<add key=\"" + key + "\" value=\"" + value + "\"/>";

                xmldoc.SelectSingleNode("/configuration").AppendChild(n2);

                xmldoc.Save(AppConfig);

            }

            else if (xmllst.Count == 0)

            {

                XmlNode n2 = xmldoc.CreateNode("element", "add", "");

                XmlAttribute xa = xmldoc.CreateAttribute("key");

                xa.Value = key;

                n2.Attributes.Append(xa);

                xa = xmldoc.CreateAttribute("value");

                xa.Value = value;

                n2.Attributes.Append(xa);

                xmldoc.SelectSingleNode("/configuration/appSettings").AppendChild(n2);

                xmldoc.Save(AppConfig);

            }

            else

            {

                bool existed = false;

                foreach (XmlNode n1 in xmllst)

                {

                    if (n1.Attributes["key"].Value.ToUpper() == key.ToUpper())

                    {

                        n1.Attributes["value"].Value = value;

                        xmldoc.Save(AppConfig);

                        existed = true;

                        break;

                    }

                }

                if (!existed)

                {

                    XmlNode xmlnd = xmldoc.SelectSingleNode("/configuration/appSettings");

                    XmlNode n2 = xmldoc.CreateNode("element", "add", "");

                    XmlAttribute xa = xmldoc.CreateAttribute("key");

                    xa.Value = key;

                    n2.Attributes.Append(xa);

                    xa = xmldoc.CreateAttribute("value");

                    xa.Value = value;

                    n2.Attributes.Append(xa);

                    xmlnd.AppendChild(n2);

                    xmldoc.Save(AppConfig);

                }

            }

            ConfigurationManager.RefreshSection("appSettings");

        }

    }

}

更改App.config里的值并保存的更多相关文章

  1. winform程序读取和改写配置文件App.config元素的值

    winform程序读取和改写配置文件App.config元素的值 2016-05-16 17:49 by newbirth, 2412 阅读, 0 评论, 收藏, 编辑 1 2 3 4 5 6 7 & ...

  2. .net里面<app.config>中value值不能填写特殊符号问题

    配置app.config或web.config的时候,经常要填写value值, 但是value值不能包含特殊字符,需要转义, 分享一下转义字符 App.config 实际上是 xml 文件,在标准 x ...

  3. c# 修改winform中app.config的配置值

    public bool ChangeConfig(string AppKey,string AppValue) { bool result = true; try { XmlDocument xDoc ...

  4. 如何修改Web.Config里面的值

    0.先添加 <add key="MAXNUM" value="6" /> 1.读取值 string maxNum = ConfigurationMa ...

  5. app.config中的值获取及设置 以及对log4net配置

      修改或新增AppSetting节点 /// <summary> /// 修改AppSettings中配置 /// </summary> /// <param name ...

  6. c#配置文件app.config 与 Settings.settings

    本篇博客将介绍C#中Settings的使用.参考:https://docs.microsoft.com/zh-cn/visualstudio/ide/managing-application-sett ...

  7. 【flask】flask项目配置 app.config

    [理论] 在很多情况下,你需要设置程序的某些行为,这时你就需要使用配置变量.在Flask中,配置变量就是一些大写形式的Python变量, 你也可以称之为配置参数或配置键.使用统一的配置变量可以避免在程 ...

  8. C#的配置文件App.config使用总结 - 转

    http://blog.csdn.net/celte/article/details/9749389 首先,先说明,我使用的app.config 配置文件的格式如下: <?xml version ...

  9. app.config应该放哪?

    一:做了一个简单的三层构架的小例子,在主项目里调用工具类的方法实现在数据库里添加一条信息.先看下错误的提示信息是什么样的,如下图一,图二是调用工具类.直接在工具类里写上连接字符串就没问题,如果写到ap ...

随机推荐

  1. 如何在mybatis中引用java中的常量和方法

    转自:http://www.68idc.cn/help/jiabenmake/qita/20140821125261.html 在mybatis的映射xml文件调用java类的方法: 1. SELEC ...

  2. Redis系列(二)--分布式锁、分布式ID简单实现及思路

    分布式锁: Redis可以实现分布式锁,只是讨论Redis的实现思路,而真的实现分布式锁,Zookeeper更加可靠 为什么使用分布式锁: 单机环境下只存在多线程,通过同步操作就可以实现对并发环境的安 ...

  3. js数组的处理

    //重写Array中的indexOf方法,获取数组中指定值的元素的索引 Array.prototype.indexOf = function (val) { for (var i = 0; i < ...

  4. java计算两地距离(公里)

    //目标经度,目标纬度,自己经度,自己纬度 public static double getDistance(double lon1, double lat1, double lon2, double ...

  5. 诊断:expdp导出时遇到错误ORA-31693和ORA-00922

    11.2.0.1使用数据泵expdp导出时,如果使用parallel,可能会遇到 ORA-: Table data object "OWNER"."TABLE" ...

  6. Linux下“任务管理器”

    也不知道linux叫不叫任务管理器. Ctrl+Alt+T打开终端,输入top,就会出现一堆东西. 如果有个东西未响应了,就可以输入k+这个进程的pid就可以杀死它. https://blog.csd ...

  7. LearnPython笔记:ex48 代码

    赶紧写上 ,一定有人着急要看,啊哈哈哈哈,嘻嘻 哈哈 不枉我起了个大早 利用什么碎片时间啊,真正能深入学习的,是需要大段大段不被打断的时间 1. 完全实现了如下几种输入数据: 2. 遗留:最后一个el ...

  8. exists关键词和case表达式

    首先声明一下,exist和case没有必然联系,这里只是为了一起整理个笔记. EXIST谓词 如果存在对应的记录,返回TRUE.否则,返回FALSE.*实际使用中,即使不适用exist,基本也可以使用 ...

  9. RequestMapping_请求参数&请求头

    params和headers支持简单的表达式: --param1:表示请求必须包含名为param1的请求参数. --!param1:表示请求不能包含名为param1的请求参数. --param1 != ...

  10. validate针对checkbox、radio、select标签的验证

    jQuery.validate 是jquery的一个插件,用来辅助开发者在客户端方便快捷的实现表单验证,最终达到提高用户体验的目的. 示例代码 <form id="formLogin& ...