XML文件和webconfig文件操作

来源:互联网 发布:搜狗输入法linux版 编辑:程序博客网 时间:2024/05/19 16:29

XML文件和webconfig文件操作

                                       【原作者: China_彬

//定义

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Configuration;
//********************************************************************************
//文 件 名:clsOperateXML.cs
//*********************************************************************************

namespace ConnectSetting
{
    public class clsOperateXML
    {

        //类的构造函数,传递XML文件名
        XmlDocument doc;
        string sXMLPath;
        public clsOperateXML(string ssXMLPath)
        {
            //
            // TODO: Add constructor logic here
            //
            this.sXMLPath = ssXMLPath;
            doc = new XmlDocument( );
            try
            {
                doc.Load( ssXMLPath );
               
            }
            catch (Exception ex)
            {
                MessageBox.Show( "系统配置文件不存在或是已破坏!", "错误提示" );
            }
        }

        //读取XML文件指定
        ///


        ///
        ///

        /// 部分
        /// 关键字
        ///
        public string XmlReadValue(string Section, string Key)
        {
            XmlNode XmlCodeNode = doc.SelectSingleNode( "//"+Section );

            string ss = "";
            if (null != XmlCodeNode)
            {
                ss = XmlCodeNode.SelectSingleNode( Key ).InnerText;
            }
            return ss;

        }
        //写XML文件
        public void XmlWriteValue(string Section, string Key, string Value)
        {
            XmlNode XmlCodeNode = doc.SelectSingleNode( "//" + Section );

            if (null != XmlCodeNode)
            {
                XmlCodeNode.SelectSingleNode( Key ).InnerText=Value;
            }
            doc.Save( sXMLPath );
        }

        //读取web.config文件指定 
        /// 关键字
        ///
        public string ConfReadValue(string key)
        {
            string svalue = "";
            try
            {
               svalue = System.Configuration.ConfigurationSettings.AppSettings[key];
            }
            catch (Exception ex)
            {
                MessageBox.Show("未找到参数!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return svalue;
        }
        //写web.config
        ///


        /// 修改web.config文件appSettings配置节中的Add里的value属性
        ///

        ///
        /// 注意,调用该函数后,会使整个Web Application重启,导致当前所有的会话丢失
        ///

        /// 要修改的键key
        /// 修改后的value
        /// 找不到相关的键
        /// 权限不够,无法保存到web.config文件中

        public void ConfWriteValue(string key,string strValue)
        {
            string XPath="/configuration/appSettings/add[@key='?']";
            //XmlDocument domWebConfig=new XmlDocument();

            //domWebConfig.Load( (HttpContext.Current.Server.MapPath("web.config")) );
            XmlNode addKey=doc.SelectSingleNode( (XPath.Replace("?",key)) );
            if(addKey == null)
            {
            throw new ArgumentException("没有找到的配置节");
            }
            addKey.Attributes["value"].InnerText=strValue;
            doc.Save(sXMLPath);
           
        }
    }
}

//调用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ConnectSetting
{
    public partial class frmWebServicesConf : Form
    {
        clsOperateXML xml = new clsOperateXML(Application.StartupPath + @"/web.config");

        public frmWebServicesConf()
        {
            InitializeComponent();
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            //if (xml.XmlReadValue("connection", "DBType").ToUpper() == "ORACLE")
            //{
                conn.ConnectionString = "Provider=/"OraOLEDB.Oracle.1/";User ID=" + this.txtUserID.Text + ";Data Source=" + this.txtService.Text + ";Extended Properties=;Per" +
                "sist Security Info=True;Password=" + this.txtPW.Text;
            //}
            //else if (xml.XmlReadValue("connection", "DBType").ToUpper() == "ACCESS")
            //{
            //    conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;data source=" + this.buttonEdit1.Text;
            //}
            try
            {
                conn.Open();
                MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            if (this.txtService.Text.Trim( ).Length <= 0)
            {
                MessageBox.Show( "服务名信息为空!请填写", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
                this.txtService.Focus( );
                return;
            }
            if (this.txtUserID.Text.Trim( ).Length <= 0)
            {
                MessageBox.Show( "用户名信息为空!请填写", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
                this.txtUserID.Focus( );
                return;
            }
            if (this.txtPW.Text.Trim( ).Length <= 0)
            {
                MessageBox.Show( "密码信息为空!请填写", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information );
                this.txtPW.Focus( );
                return;
            }

            //xml.XmlWriteValue("connection", "DBServerName", this.txtService.Text.Trim());
            //xml.XmlWriteValue("connection", "userName", this.txtUserID.Text.Trim());
            //xml.XmlWriteValue("connection", "password", this.txtPW.Text.Trim());
            xml.ConfWriteValue("Database", this.txtService.Text.Trim());
            xml.ConfWriteValue("UserName", this.txtUserID.Text.Trim());
            xml.ConfWriteValue("Password", this.txtPW.Text.Trim());

            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

//附xml和web.config事例

web.config

《?xml version="1.0"?》
《configuration》
 《appSettings》
  《!--用户权限服务--》
  《add key="Database" value="rjborcl"/》
  《add key="UserName" value="quanxian"/》
  《add key="Password" value="quanxian"/》
 《/appSettings》
 《system.web》......

xml

《?xml version="1.0" encoding="UTF-8"?》
《lsAppConf》
 《connection name="edit" password="edit" class="" inited="true"》
  《userName》quanxian《/userName》
  《password》quanxian《/password》
  《DBServerName》rjborcl《/DBServerName》
 《/connection》
《/lsAppConf》

【作者: China_彬】【访问统计: 28】【2008年04月10日 星期四 14:51】

原创粉丝点击