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
  • 相关阅读:
    docker在Linux环境下的安装
    docker在Windows环境下的安装
    tcpdump和windump
    Centos7下安装Elasticsearch 5.6.6
    使用concurrent.futures模块并发,实现进程池、线程池
    Nginx配置Gzip
    linux常用命令
    Linux下文档与目录结构
    快速读取大文件的几种方式
    linux 将大文件分解为多个小文件
  • 原文地址:https://www.cnblogs.com/yonsy/p/5606920.html
Copyright © 2011-2022 走看看