zoukankan      html  css  js  c++  java
  • Asp.net使用代码修改配置文件的节点值

    使用代码修改配置文件的方法:

    1、打开配置文件写入的权限

    2、先按节点名称长到要修改的节点,然后删除,紧接着将有新值的节点添加回去

    3、关闭配置文件写入的权限

    修改Appsetting节点的值,修改其它节点的方法也差不多,也是找到要修改的节点删除掉然后新新值的节点加上

            public bool UpdateAppSettings(string key, string value)
            {
                bool reuslt = false;
    
                try
                {
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    SetFileAccess(config.FilePath + "", false);
                    ConfigurationSection sections = config.GetSection("appSettings");
                    bool isSet = false;
                    for (int i = 0; i < ((System.Configuration.AppSettingsSection)(sections)).Settings.Count; i++)
                    {
                        string itemkey = ((System.Configuration.AppSettingsSection)(sections)).Settings.AllKeys[i];
                        if (itemkey == key)
                        {
                            ((System.Configuration.AppSettingsSection)(sections)).Settings.Remove(key);
                            ((System.Configuration.AppSettingsSection)(sections)).Settings.Add(key, value);
                            isSet = true;
                            break;
                        }
                    }
                    if (!isSet)
                    {
                        ((System.Configuration.AppSettingsSection)(sections)).Settings.Add(key, value);
                    }
    
                    config.Save();
                    ConfigurationManager.RefreshSection("appSettings");
    
                    SetFileAccess(config.FilePath + "", true);
                    reuslt = true;
                }
                catch (Exception ex)
                {
                    LogNet.Log.WriteLog("UpdateAppSettings", ex);
                }
    
                return reuslt;
            }
    View Code

    修改配置文件的读写权限

            protected void SetFileAccess(string path, bool isReadOnly)
            {
                FileInfo fi = new FileInfo(path);
                if (fi.IsReadOnly != isReadOnly)
                    fi.IsReadOnly = isReadOnly;
            }
    View Code
  • 相关阅读:
    信息爆炸时代,对待信息的三种方式
    Spring事务管理
    归并排序和快速排序的衍生问题
    Linux之Shell命令
    程序员找工作的干货经验
    css3 Transition动画执行时有可能会出现闪烁的bug
    布尔值
    null, undefined理解
    js文字的无缝滚动(上下)
    vue实现文字上下滚动
  • 原文地址:https://www.cnblogs.com/yonsy/p/5606920.html
Copyright © 2011-2022 走看看