.net用代码配置Web.config文件

简介: public class Webconfig     {         private string XmlFilePath;         private XmlDocument xmldoc;         #region 构造...

public class Webconfig
    {
        private string XmlFilePath;
        private XmlDocument xmldoc;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="FilePath">配置文件的路径</param>
        public Webconfig(string FilePath)
        {
            XmlFilePath = FilePath;
            xmldoc = new XmlDocument();//新xml文档对象
            if (File.Exists(XmlFilePath)) xmldoc.Load(XmlFilePath);  //如果文件存在,则加载现有的xml文档
        }
        #endregion

        #region 设置和获得AppSettings的值
        /// <summary>
        /// 获得AppSetting的值
        /// </summary>
        /// <param name="KeyName">节点名(key的值)</param>
        /// <returns></returns>
        public string AppSetting_Get(string KeyName)
        {
            XmlNodeList list = xmldoc.SelectNodes("/configuration/appSettings/add");
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("key") == KeyName) return xe.GetAttribute("value");
            }
            return "";

        }

        /// <summary>
        /// appSettings下的配置字符串
        /// </summary>
        /// <param name="KeyName">key的值</param>
        /// <param name="ValueString">value的值</param>
        public void AppSetting_Set(string KeyName, string ValueString)
        {
            InitNode("/configuration/appSettings");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/appSettings/add");
            if (ValueString == "")
            {
                ValueString = "Data Source=.;Initial Catalog=数据库名;uid=用户名;pwd=密码";
            }
            bool isexist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("key") == KeyName)
                {
                    xe.SetAttribute("value", ValueString);
                    isexist = true;
                }
            }
            if (!isexist)
            {
                XmlElement xe1 = xmldoc.CreateElement("add");
                xe1.SetAttribute("key", KeyName);
                xe1.SetAttribute("value", ValueString);
                xmldoc.SelectSingleNode("/configuration/appSettings").AppendChild(xe1);
            }
            xmldoc.Save(XmlFilePath);

        }

        #endregion

        #region httpModules下的配置字符串

        public void httpModules_Set()
        {
            InitNode("/configuration/system.web/httpModules");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/system.web/httpModules/add");
            bool isexist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("name") == "MyModule")
                {
                    xe.SetAttribute("type", "Tools.Mymodule,Tools");
                    isexist = true;
                }

            }
            if (!isexist)
            {
                XmlElement xe1 = xmldoc.CreateElement("add");
                xe1.SetAttribute("name", "MyModule");
                xe1.SetAttribute("type", "Tools.Mymodule,Tools");
                xmldoc.SelectSingleNode("/configuration/system.web/httpModules").AppendChild(xe1);
            }
            xmldoc.Save(XmlFilePath);

        }
        #endregion

        #region 设置sessionState的字符串

        public void SessionState_Set()
        {
            InitNode("/configuration/system.web/sessionState");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/sessionState");
            xe.SetAttribute("mode", "StateServer");
            xe.SetAttribute("stateConnectionString", "tcpip=localhost:42424");
            xe.SetAttribute("sqlConnectionString", "data source=127.0.0.1;Trusted_Connection=yes");
            xe.SetAttribute("cookieless", "false");
            xe.SetAttribute("timeout", "40");
            xmldoc.Save(XmlFilePath);
        }
        #endregion

        #region 设置httpRuntime的字符串

        public void httpRuntime_Set()
        {
            InitNode("/configuration/system.web/httpRuntime");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/httpRuntime");
            xe.SetAttribute("maxRequestLength", "2048000");
            xe.SetAttribute("executionTimeout", "900");
            xe.SetAttribute("useFullyQualifiedRedirectUrl", "true");
            xe.SetAttribute("appRequestQueueLimit", "150");
            xe.SetAttribute("minFreeThreads", "18");
            xe.SetAttribute("minLocalRequestFreeThreads", "15");
            xmldoc.Save(XmlFilePath);
        }
        #endregion

        #region 设置customErrors的字符串

        public void customErrors_Set()
        {
            InitNode("/configuration/system.web/customErrors");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/customErrors");
            xe.SetAttribute("mode", "RemoteOnly");
            xe.SetAttribute("redirectMode", "ResponseRewrite");
            xe.SetAttribute("defaultRedirect", "~/一般错误提示.aspx");
            XmlNodeList list = xe.ChildNodes;
            bool[] isexist = { false, false };
            foreach (XmlNode node in list)
            {
                XmlElement element = (XmlElement)node;
                if (element.GetAttribute("statusCode") == "403")
                {
                    element.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
                }
                else if (element.GetAttribute("statusCode") == "403")
                {
                }
            }
            XmlElement xe1 = null;
            if (isNodeExist(list, "statusCode", "403", ref xe1))
            {
                xe1.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
            }
            else
            {
                xe1 = xmldoc.CreateElement("error");
                xe1.SetAttribute("statusCode", "403");
                xe1.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
                xe.AppendChild(xe1);
            }

            XmlElement xe2 = null;
            if (isNodeExist(list, "statusCode", "404", ref xe2))
            {
                xe2.SetAttribute("redirect", "~/找不到时的提示页面.aspx");
            }
            else
            {
                xe2 = xmldoc.CreateElement("error");
                xe2.SetAttribute("statusCode", "404");
                xe2.SetAttribute("redirect", "~/找不到时的提示页面.aspx");
                xe.AppendChild(xe2);
            }
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 查询是否存在结点 isNodeExist
        /// <summary>
        /// 查询是否存在结点 isNodeExist
        /// </summary>
        /// <param name="list">节点列表</param>
        /// <param name="AttrKey">属性键名</param>
        /// <param name="AttrValue">属性值</param>
        /// <param name="Element">引用的XmlElement值</param>
        /// <returns></returns>
        public bool isNodeExist(XmlNodeList list, string AttrKey, string AttrValue, ref XmlElement Element)
        {
            bool isExist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute(AttrKey) == AttrValue)
                {
                    isExist = true;
                    Element = xe;
                    break;
                }
            }
            return isExist;
        }
        #endregion

        #region 设置configSections下的log4net的字符串

        public void configSections_Set_log4net()
        {
            InitNode("/configuration/configSections");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/configSections");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/configSections/section");
            XmlElement Log4Net=null;
            if (isNodeExist(list, "name", "log4net", ref Log4Net))
            {
                Log4Net.SetAttribute("type", "log4net.Config.Log4NetConfigurationSectionHandler, log4net");
            }
            else
            {
                Log4Net = xmldoc.CreateElement("section");
                Log4Net.SetAttribute("name","log4net");
                Log4Net.SetAttribute("type", "log4net.Config.Log4NetConfigurationSectionHandler, log4net");
                xe.InsertBefore(Log4Net,xe.FirstChild);//在xe节点下插入子节点,插在最前
            }
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 设置log4net的字符串

        public void log4net_Set()
        {
            XmlComment xc;
            InitNode("/configuration/log4net");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/log4net");
           
            xc = xmldoc.CreateComment("在 Global类中Application_Start函数中加入 log4net.Config.XmlConfigurator.Configure();");
            xe.AppendChild(xc);
            xc = xmldoc.CreateComment("用之前得到对象: private ILog logger = LogManager.GetLogger(typeof(类名));");
            xe.AppendChild(xc);

            XmlElement xe2;
            string logNodePath = "/configuration/log4net/appender";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("name","RollingLogFileAppender");
            xe2.SetAttribute("type", "log4net.Appender.RollingFileAppender");

            logNodePath = "/configuration/log4net/appender/file";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "Log4net.log");

            logNodePath = "/configuration/log4net/appender/appendToFile";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "true");

            logNodePath = "/configuration/log4net/appender/maxSizeRollBackups";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "10");

            logNodePath = "/configuration/log4net/appender/maximumFileSize";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "1024KB");

            logNodePath = "/configuration/log4net/appender/rollingStyle";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "Size");

            logNodePath = "/configuration/log4net/appender/staticLogFileName";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "true");

            logNodePath = "/configuration/log4net/appender/layout";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("type", "log4net.Layout.PatternLayout");

            logNodePath = "/configuration/log4net/appender/layout/conversionPattern";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "%date [%thread] %-5level %logger - %message%newline");

            InitNode("/configuration/log4net/root");

            logNodePath = "/configuration/log4net/root/level";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value","DEBUG");

            logNodePath = "/configuration/log4net/root/appender-ref";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("ref", "RollingLogFileAppender");
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 设置system.web下的identity的字符串

        public void identity_Set()
        {
            InitNode("/configuration/system.web/identity");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/identity");
            xe.SetAttribute("impersonate", "true");
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 初始化全部路径
        /// <summary>
        /// 初始化全部路径
        /// </summary>
        /// <param name="FilePath">内部为Xml格式的文件路径</param>
        /// <param name="NodePath">相对于根的节点路径</param>
        /// <returns>提示信息,ok为成功</returns>
        public string InitNode(string NodePath)
        {
            string Result = "ok";

            string[] nodes = NodePath.Trim('/').Split('/');
            XmlNode node = xmldoc.SelectSingleNode(NodePath.TrimEnd('/'));
            if (node == null) //如果不存在,则要创建和保存
            {
                XmlNode nodeParent;
                XmlNode nodeTemp;
                XmlElement ElementNew;
                string tempPath = "";//当前节点路径
                string parentPath = "";//父节点路径
                for (int i = 0; i < nodes.Length; i++)
                {
                    tempPath += "/" + nodes[i];
                    nodeTemp = xmldoc.SelectSingleNode(tempPath);
                    if (nodeTemp == null)
                    {
                        ElementNew = xmldoc.CreateElement(nodes[i]);
                        if (parentPath == "")
                        {
                            if (xmldoc.HasChildNodes)
                            {
                                Result = "此文档已有根结点,不能再创建一个根结点!";
                                return Result;
                            }
                            else xmldoc.AppendChild(ElementNew);
                        }
                        else
                        {
                            nodeParent = xmldoc.SelectSingleNode(parentPath);
                            nodeParent.AppendChild(ElementNew);
                        }
                    }
                    parentPath = tempPath;

                }
                xmldoc.Save(XmlFilePath);
            }
            return Result;
        }
        #endregion

    }

 

相关文章
|
13天前
Visual Studio 快速分析 .NET Dump 文件
【11月更文挑战第10天】.NET Dump 文件是在 .NET 应用程序崩溃或出现问题时生成的,记录了应用程序的状态,包括内存对象、线程栈和模块信息。通过分析这些文件,开发人员可以定位和解决内存泄漏、死锁等问题。在 Visual Studio 中,可以通过调试工具、内存分析工具和符号加载等功能来详细分析 Dump 文件。此外,还可以使用第三方工具如 WinDbg 进行更深入的分析。
|
2月前
|
计算机视觉 Python
Flask学习笔记(六):基于Flask的摄像头-web显示代码(可直接使用)
这篇文章是关于如何使用Flask框架结合OpenCV库,通过电脑摄像头实现视频流在网页上的实时显示,并提供了单摄像头和多摄像头的实现方法。
89 2
Flask学习笔记(六):基于Flask的摄像头-web显示代码(可直接使用)
|
2月前
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
Android远程连接和登录FTPS服务代码(commons.net库)
24 1
|
2月前
|
JavaScript 前端开发 应用服务中间件
vue前端开发中,通过vue.config.js配置和nginx配置,实现多个入口文件的实现方法
vue前端开发中,通过vue.config.js配置和nginx配置,实现多个入口文件的实现方法
158 0
|
2月前
|
C# Windows
一款基于.NET开发的简易高效的文件转换器
一款基于.NET开发的简易高效的文件转换器
|
2月前
|
前端开发 JavaScript C#
CodeMaid:一款基于.NET开发的Visual Studio代码简化和整理实用插件
CodeMaid:一款基于.NET开发的Visual Studio代码简化和整理实用插件
|
3月前
|
XML JSON 安全
Web安全-代码注入
Web安全-代码注入
26 6
|
3月前
.NET 压缩/解压文件
【9月更文挑战第5天】在 .NET 中,可利用 `System.IO.Compression` 命名空间进行文件的压缩与解压。首先引入相关命名空间,然后通过 GZipStream 类实现具体的压缩或解压功能。下面提供了压缩与解压文件的方法示例及调用方式,便于用户快速上手操作。
|
4月前
|
数据库 开发者 Java
数据战争:Hibernate的乐观与悲观锁之争,谁将主宰并发控制的王座?
【8月更文挑战第31天】在软件开发中,数据一致性至关重要,尤其是在多用户并发访问环境下。Hibernate 作为 Java 社区常用的 ORM 框架,提供了乐观锁和悲观锁机制来处理并发问题。乐观锁假设数据不易冲突,通过版本号字段 (`@Version`) 实现;悲观锁则假定数据易冲突,在读取时即加锁。选择哪种锁取决于具体场景:乐观锁适合读多写少的情况,减少锁开销;悲观锁适合写操作频繁的场景,避免数据冲突。正确应用这些机制可提升应用程序的健壮性和效率。
36 0
|
4月前
|
Java UED 自然语言处理
Struts 2 国际化竟有如此神奇魔力?快来揭开多语言支持的 Web 应用神秘面纱
【8月更文挑战第31天】在全球化背景下,Web应用需适应多种语言环境。Struts 2凭借其强大的国际化(i18n)支持,简化了多语言应用开发。通过不同语言的资源文件,它能自动匹配用户语言偏好,优化用户体验并扩展用户群。下面是一个示例:创建`messages.properties`(英语)与`messages_zh_CN.properties`(中文),并在Struts 2的Action类及JSP页面中调用`getText()`方法及Struts标签展示相应语言内容。此外,在struts.xml中指定资源文件,以确保框架正确加载对应语言包。通过这些步骤,开发者可以轻松实现应用的多语言支持。
65 0
下一篇
无影云桌面