.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

    }

 

相关文章
|
1月前
|
开发框架 .NET C#
ASP.NET Core Blazor 路由配置和导航
大家好,我是码农刚子。本文系统介绍Blazor单页应用的路由机制,涵盖基础配置、路由参数、编程式导航及高级功能。通过@page指令定义路由,支持参数约束、可选参数与通配符捕获,结合NavigationManager实现页面跳转与参数传递,并演示用户管理、产品展示等典型场景,全面掌握Blazor路由从入门到实战的完整方案。
221 6
|
6月前
|
前端开发
自动生成md文件以及config.mjs文件-vitepress
自动生成md文件以及config.mjs文件-vitepress
217 59
|
6月前
|
XML 安全 前端开发
一行代码搞定禁用 web 开发者工具
在如今的互联网时代,网页源码的保护显得尤为重要,特别是前端代码,几乎就是明文展示,很容易造成源码泄露,黑客和恶意用户往往会利用浏览器的开发者工具来窃取网站的敏感信息。为了有效防止用户打开浏览器的 Web 开发者工具面板,今天推荐一个不错的 npm 库,可以帮助开发者更好地保护自己的网站源码,本文将介绍该库的功能和使用方法。 功能介绍 npm 库名称:disable-devtool,github 路径:/theajack/disable-devtool。从 f12 按钮,右键单击和浏览器菜单都可以禁用 Web 开发工具。 🚀 一行代码搞定禁用 web 开发者工具 该库有以下特性: • 支持可配
412 22
|
7月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
337 35
|
11月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
9月前
|
开发工具 git 索引
怎么取消对project.private.config.json这个文件的git记录
通过以上步骤,您可以成功取消对 `project.private.config.json`文件的Git记录。这样,文件将不会被包含在未来的提交中,同时仍保留在您的工作区中。
265 28
|
11月前
|
运维 前端开发 C#
一套以用户体验出发的.NET8 Web开源框架
一套以用户体验出发的.NET8 Web开源框架
301 7
一套以用户体验出发的.NET8 Web开源框架
|
10月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
192 14
|
11月前
|
算法 Java 测试技术
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
281 13
|
11月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。

热门文章

最新文章