一个用于读写配置文件的类
该类适应读写如下格式的.xml,.config文档
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!--This is a config file ,writer by furenjun-->
<configuration>
  <appSettings>
    <add key="SqlStr0" value="0" />
    <add key="SqlStr1" value="1" />
    <add key="2006-7-3 16:05:08" value="1" />
  </appSettings>
</configuration>

using System;
using System.Configuration ;
using System.Reflection ;
using System.Xml;
using System.IO;
using System.Collections.Specialized;
using System.Collections;
using System.Data ;
using System.Diagnostics;
using System.Windows.Forms;
namespace 读写配置文件
{
    /**//// <summary>
    /// MrfuRWXmlFile 的摘要说明。
    /// </summary>
    public class MrfuRWXmlFile
    {
        public static string ConfigFullName="";
    
        
        private NameValueCollection appSettings = null;
        public MrfuRWXmlFile()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            //            Assembly MyAssembly= Assembly.GetExecutingAssembly();
            //            string ConfigLocPath=MyAssembly.Location;
            //            string strDireName=Path.GetDirectoryName(ConfigLocPath) ;
            //            //MessageBox.Show(ConfigLocPath+"\n"+strDireName) ;
            //            ConfigFullName=ConfigLocPath+".config";
            ConfigFullName=Application.StartupPath+@"\myProject.config" ;
            
            //MessageBox.Show(ConfigFullName) ;
        }
        private static void CreateNewXmlFile()
        {
            XmlTextWriter myXmlTextWriter = new XmlTextWriter (ConfigFullName, System.Text.Encoding.UTF8 );
            myXmlTextWriter.Formatting = Formatting.Indented;
            myXmlTextWriter.WriteStartDocument(false); //设置standalone="no"   //当为(true)时 <?xml version="1.0" standalone="yes" ?> 
            //    myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
            myXmlTextWriter.WriteComment("This is a config file ,writer by furenjun");
            myXmlTextWriter.WriteStartElement("configuration");
            myXmlTextWriter.WriteStartElement("appSettings", null);
            '写入其它元素'#region '写入其它元素'
            //            myXmlTextWriter.WriteAttributeString("genre","autobiography");
            //            myXmlTextWriter.WriteAttributeString("publicationdate","1979");
            //            myXmlTextWriter.WriteAttributeString("ISBN","0-7356-0562-9");
            //            myXmlTextWriter.WriteElementString("title", null, "The Autobiography of Mark Twain");
            //            myXmlTextWriter.WriteStartElement("Author", null);
            //            myXmlTextWriter.WriteElementString("first-name", "Mark");
            //            myXmlTextWriter.WriteElementString("last-name", "Twain");
            //            myXmlTextWriter.WriteEndElement();
            //            myXmlTextWriter.WriteElementString("price", "7.99");
            #endregion
            myXmlTextWriter.WriteEndElement();
            myXmlTextWriter.WriteEndElement();

            //Write the XML to file and close the myXmlTextWriter
            myXmlTextWriter.Flush();
            myXmlTextWriter.Close();
        }
        public MrfuRWXmlFile(string ConfigFilePath)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
    
            ConfigFullName=ConfigFilePath;
            
        }

        public string GsConfigFilePath
        {
            get{return ConfigFullName;}
            set{ConfigFullName=value;}
        }

        //初始化xml文档
        //首先请右击"项目"-->添加一个新项-->选择"应用程序配置文件"-->点击确定
        public static bool CreateXmlFile()
        {
            if(!File.Exists(ConfigFullName) )
                CreateNewXmlFile();

            bool bflag=true;
            ConfigXmlDocument configXmlDoc=new ConfigXmlDocument();//  XmlDocument();
            configXmlDoc.Load(ConfigFullName) ;
            //检查结点是否存在#region //检查结点是否存在
            //            //XmlNodeList xList=configXmlDoc.SelectNodes ("//appSettings");//可以根据实际需要更改它的查找范围.如SelectNodes("//User")
            //            XmlNodeList xList=configXmlDoc.DocumentElement.ChildNodes  ;
            //            
            //
            //            if (xList.Count> 0)
            //            {
            //                
            //            
            //                foreach(XmlNode node in xList)
            //                {
            //                    if(node.Name =="appSettings")
            //                        MessageBox.Show ("找到");
            //                    return;
            //                }
            //            }
            //            else
            //            {
            //                MessageBox.Show("no nodes") ;
            //            }
            //
            //            XmlNode root2 = configXmlDoc.FirstChild;
            //
            //            //Display the contents of the child nodes.
            //            if (root2.HasChildNodes)
            //            {
            //                string strs="";
            //                for (int i=0; i<root2.ChildNodes.Count; i++)
            //                {
            //                    strs+=(root2.ChildNodes[i].InnerText)+"\n";
            //                }
            //                MessageBox.Show(strs) ;
            //            }

            #endregion
            XmlNode appSettingsNode;
            appSettingsNode = configXmlDoc.SelectSingleNode("configuration/appSettings");
            
            if(appSettingsNode.LocalName=="appSettings")  //或者(appSettingNode!=null)
            {
                //如果xml文档中已存在该结点则采用选择定位该结点的方法
                appSettingsNode.RemoveAll();
                //MessageBox.Show(appSettingsNode.LocalName) ;
            }
            else
            {
                // Create a new element node.
                XmlNode newElem;
                newElem = configXmlDoc.CreateNode(XmlNodeType.Element, "appSettings", "");  
                //newElem.InnerText = "290";
                //"Add the new element to the document"
                XmlElement root = configXmlDoc.DocumentElement;
                root.AppendChild(newElem);
                //("Display the modified XML document");
                //Console.WriteLine(configXmlDoc.OuterXml);
                appSettingsNode =newElem;
            }
            try
            {        
                for (int i = 0; i < 2; i++)
                {
                    string key = "SqlStr"+i.ToString() ;
                    string val = i.ToString() ;
                    
                    //创建结点
                    XmlNode node = configXmlDoc.CreateNode(XmlNodeType.Element, "add", "");

                    //创建属性"key"并为其赋值
                    XmlAttribute attr = configXmlDoc.CreateAttribute("key");
                    attr.Value = key;
                    node.Attributes.Append(attr);
                    //创建属性"value"并为其赋值
                    attr = configXmlDoc.CreateAttribute("value");
                    attr.Value = val;
                    node.Attributes.Append(attr);
                    appSettingsNode.AppendChild(node);

                }
                configXmlDoc.Save(ConfigFullName);
                
                //MessageBox.Show("创建Xml文档结点成功.","系统提示",MessageBoxButtons.OK ,MessageBoxIcon.Information ) ;
            }
            catch (Exception ex)
            {
                bflag=false;
                throw new ConfigurationException(ex.ToString() );
            }
            return bflag;
        }
        
        private void LoadFromFile()
        {
            //if (appSettings == null)
            //{
            try
            {
                //string filePath=@"E:\淄博市鲁中机动车检测中心数据联网软件\FromHlk\读写配置文件\ConfigurationSettingsRW_demo\ConfigurationSettingsRW_demo\ConfigurationSettingsRW.exe.config";
                ConfigXmlDocument configXml = new ConfigXmlDocument();//  XmlDocument();
                //configXml.Load(filePath);//this.configFilePath);
                configXml.Load(ConfigFullName);
                //MessageBox.Show(ConfigFullName ) ;
                XmlNode appSettingsNode = configXml.SelectSingleNode("configuration/appSettings");
                //MessageBox.Show(appSettingsNode.LocalName) ;
                if(appSettingsNode.LocalName=="appSettings")
                {
                    NameValueSectionHandler handler = new NameValueSectionHandler();
                    
                    
                    appSettings = new NameValueCollection((NameValueCollection)handler.Create(null, null, appSettingsNode));
                }
                
            }
            catch (Exception ex)
            {
                throw new ConfigurationException("Error while loading appSettings. Message: " + ex.Message, ex);
            }
            //}
        }


        /**//// <summary>
        /// 获取配置文件中的结点"appSettings"中的值
        /// </summary>
        /// <returns></returns>
        public DataTable GetSettingsValue()
        {
            LoadFromFile();
            DataTable tblAppSettings=new DataTable("Settings") ;
            tblAppSettings.Columns.Add("key", typeof(System.String));
            tblAppSettings.Columns.Add("value", typeof(System.String));

            for (int i = 0; i < appSettings.Count; i++)
            {
                string key = appSettings.GetKey(i);
                string val = appSettings.Get(i);
            
                DataRow row = tblAppSettings.NewRow();
                row["key"] = key;
                row["value"] = val;
                tblAppSettings.Rows.Add(row);
            }
            return tblAppSettings;
        }


        /**//// <summary>
        /// 添加一条新的纪录
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public  bool AddNewRecorder(string strKey,string strValue)
        {
            
            bool bflag=true;
            XmlDocument configXmlDoc=new XmlDocument();
            configXmlDoc.Load(ConfigFullName) ;
            
            XmlNode appSettingsNode;
            appSettingsNode = configXmlDoc.SelectSingleNode("configuration/appSettings");
            
            if(appSettingsNode==null)
            {
        
                // Create a new element node.
                XmlNode newElem;
                newElem = configXmlDoc.CreateNode(XmlNodeType.Element, "appSettings", "");  
                //newElem.InnerText = "290";
                //"Add the new element to the document"
                XmlElement root = configXmlDoc.DocumentElement;
                root.AppendChild(newElem);
                //("Display the modified XML document");
                //Console.WriteLine(configXmlDoc.OuterXml);
                appSettingsNode =newElem;
            }
            try
            {        
                
                string key = strKey;
                string val = strValue;
                    
                //创建结点
                XmlNode node = configXmlDoc.CreateNode(XmlNodeType.Element, "add", "");

                //创建属性"key"并为其赋值
                XmlAttribute attr = configXmlDoc.CreateAttribute("key");
                attr.Value = key;
                node.Attributes.Append(attr);
                //创建属性"value"并为其赋值
                attr = configXmlDoc.CreateAttribute("value");
                attr.Value = val;
                node.Attributes.Append(attr);
                appSettingsNode.AppendChild(node);

            
                configXmlDoc.Save(ConfigFullName);
                
                //MessageBox.Show("创建Xml文档结点成功.","系统提示",MessageBoxButtons.OK ,MessageBoxIcon.Information ) ;
            }
            catch (Exception ex)
            {
                bflag=false;
                throw new ConfigurationException(ex.ToString() );
            }
            return bflag;
        }

        
        /**//// <summary>
        /// Loops through the <code>appSettings</code> NameValueCollection 
        /// and recreates the XML nodes of the &lt;appSettings&gt; config 
        /// section accordingly. It saves the configuration file afterwards.
        /// </summary>
        private void SaveToFile()
        {
            if (appSettings != null)
            {
                try
                {
                    XmlDocument configXml = new XmlDocument();
                    configXml.Load(ConfigFullName);
                    XmlNode appSettingsNode = configXml.SelectSingleNode("configuration/appSettings");
                    appSettingsNode.RemoveAll();
                    for (int i = 0; i < appSettings.Count; i++)
                    {
                        string key = appSettings.GetKey(i);
                        string val = appSettings.Get(i);
                    
                        XmlNode node = configXml.CreateNode(XmlNodeType.Element, "add", "");

                        XmlAttribute attr = configXml.CreateAttribute("key");
                        attr.Value = key;
                        node.Attributes.Append(attr);

                        attr = configXml.CreateAttribute("value");
                        attr.Value = val;
                        node.Attributes.Append(attr);

                        appSettingsNode.AppendChild(node);
                    }
                    configXml.Save(ConfigFullName);
                }
                catch (Exception ex)
                {
                    throw new ConfigurationException("Error while saving appSettings.", ex);
                }
            }
        }

        /**//// <summary>
        /// 更新一条纪录
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="strNewValue"></param>
        /// <returns></returns>
        public bool  UpdateRecorder(string strKey,string strNewValue)
        {
            bool flag=true;
            try
            {
                appSettings[strKey]=strNewValue;
                SaveToFile();
            }
            catch(System.Exception err)
            {
                flag=false;
                throw new Exception(err.ToString() ) ;
            }
            return flag;
        }

        /**//// <summary>
        /// 读取一个值
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public string ReadSettingsValue(string strKey)
        {
            LoadFromFile();
            return appSettings[strKey].ToString(); 
        }

        public bool SaveDataGridChange(DataTable myTable)
        {
            bool flag=true;
            myTable.AcceptChanges(); 
            try
            {
                // Recreating the config.AppSettings collection with the data contained in appSettings DataGrid.
                appSettings.Clear();
                foreach (DataRow row in myTable.Rows)
                {
                    appSettings[row["key"].ToString()] = row["value"].ToString();
                
                }
                // Saving the appSettings data into the configuration file.
                SaveToFile();
            }
            catch(System.Exception err)
            {
                flag=false;
                throw new Exception (err.ToString() );

            }
            return flag;

        }
        // private void getTableChange(DataTable table)#region//        private void getTableChange(DataTable table)
//        {
//            
//            string missingFields = "";
//            StringCollection columnNames = new StringCollection();                
//            foreach (DataColumn col in table.Columns)
//            {
//                
//                if (missingFields.Length == 0)
//                    missingFields = col.ColumnName;
//                else 
//                    missingFields += ", " + col.ColumnName;
//                    
//            }
//                
//            if (missingFields.Length > 0)
//            {
//                throw new  Exception("Unable to update nodes with datatable because the nodes are missing the fields: "+missingFields);
//            }
//
//            ///
//            /// Remove nodes that got deleted from datatable
//            ///
//            DataTable currTable = table.GetChanges(DataRowState.Deleted);
//            if (currTable != null)
//            {
//                    
//                Trace.WriteLine("Rows Deleted:");
//                foreach (DataRow row in table.Rows)
//                {
//                    string keyValue = row[0].ToString();
//                        
//                    Trace.WriteLine(keyValue);
//                    
//                }
//            }
//
//            ///
//            /// Update nodes with changes made on the datatable
//            ///
//            currTable = table.GetChanges(DataRowState.Modified);
//            if (currTable != null)
//            {
//                    
//                Trace.WriteLine("Rows Changed:");
//                foreach (DataRow row in currTable.Rows)
//                {
//                        
//                }
//            }
//
//            ///
//            /// Add new nodes to match new rows added to datatable
//            /// 
//            currTable = table.GetChanges(DataRowState.Added);
//            if (currTable != null)
//            {
//                    
//                string keyValue;
//                    
//                Trace.WriteLine("Rows Added:");
//                foreach (DataRow row in currTable.Rows)
//                {
//                        
//                }
//            }
//            table.AcceptChanges();                
//            
//                
//        }
        #endregion

    }
}

使用:

    MrfuRWXmlFile  mrfurw=new MrfuRWXmlFile();
        private void button_Create_Click(object sender, System.EventArgs e)
        {
            MrfuRWXmlFile.CreateXmlFile(); 
            this.button_read.PerformClick();
           
            
 
        }

        private void button_read_Click(object sender, System.EventArgs e)
        {
            this.dataGrid1.DataSource=mrfurw.GetSettingsValue();
    
        }

        private void button_Update_Click(object sender, System.EventArgs e)
        {
            if(this.textBox_Value.Text.Trim()=="")
                return;
            mrfurw.UpdateRecorder("SqlStr0",this.textBox_Value.Text.Trim());
            this.button_read.PerformClick();  
  
        }

        
        int i=0;
        private void button_Add_Click(object sender, System.EventArgs e)
        {
            i+=1;
            mrfurw.AddNewRecorder( System.DateTime.Now.ToString(),i.ToString());  
            this.button_read.PerformClick();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            MessageBox.Show (mrfurw.ReadSettingsValue("SqlStr0" ));
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
               
            DataTable myTable=(DataTable)dataGrid1.DataSource;
            mrfurw.SaveDataGridChange(myTable);
        }
posted on 2006-07-03 16:18 DotNet编程 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/furenjun/archive/2006/07/03/441576.html

一个用于读写配置文件的类相关推荐

  1. 设计一个用于人事管理的“人员”类

    设计一个用于人事管理的(人员)类.考虑到通用性,这里只抽象出所有类型人员都具有的属性:编号.性别.出生日期.身份证号等.其中"出生日期"声明为一个"日期"类内嵌 ...

  2. 一个用于分页的page类

    今天周一,趁工作轻松,自己就写了一个基于MySQl数据库的分页查询,做分页,最主要的是以下几点: 一:写sql语句:比如查询某张数据表的数据,sql语句为:select * from table li ...

  3. .Net里一个用于驱动摄像头的类

    using System;using System.Runtime.InteropServices;using System.Drawing;using System.Drawing.Imaging; ...

  4. php超链接_一个纯PHP库,用于读写文字处理文档

    PHPWord是一个用纯PHP编写的库,它提供了一组用于读写不同文档文件格式的类.当前版本的PHPWord支持Microsoft Office Open XML(OOXML或OpenXML),用于Of ...

  5. Java黑皮书课后题第10章:*10.10(Queue类)10.6节给出一个Stock类。设计一个名为Queue的类用于存储整数。像栈一样,队列保存元素。在栈中,元素后进先出。队列中元素先进先出

    10.10(Queue类)10.6节给出一个Stock类,设计一个名为Queue的类用于存储整数 题目 程序 破题 代码 Test10.java Test10_Queue.java UML 题目 程序 ...

  6. Java黑皮书课后题第9章:*9.6(秒表)设计一个名为StopWatch的类,该类包含……。编写一个测试程序,用于测量使用选择排序对100000个数字进行排序的执行时间

    Java黑皮书课后题第9章:*9.6(秒表)设计一个名为StopWatch的类,该类包含--.编写一个测试程序,用于测量使用选择排序对100000个数字进行排序的执行时间 题目 破题 代码 Test6 ...

  7. 实验3.3 设计一个用于人事管理的People(人员)类

    题目 (选做)设计一个用于人事管理的People(人员)类.考虑到通用性,这里只抽象出所有类型人员都具有的属性:number(编号).sex(性别).birthday(出生日期).id(身份证号)等等 ...

  8. 设计一个用于人事管理的People(人员)类(c++)

    问题描述: 设计一个用于人事管理的People(人员)类.考虑到通用性,这里只抽象出所有类型人员都具有的属性:number(编号).sex(性别).birthday(出生日期).id(身份证号)等等. ...

  9. C++小作业-设计一个用于人事管理的People(人员)类

    一.问题描述 [问题描述]设计一个用于人事管理的People(人员)类.考虑到通用性,这里只抽象出所有类型人员都具有的属性:姓名char name[11].编号char number[7].性别cha ...

最新文章

  1. ssh免密连接远程服务器
  2. 成功解决ERROR: Could not find a version that satisfies the requirement xgboost (from versions: none) ERR
  3. python源码精要(7)-CPython编译
  4. Raspberry PI 系列 —— 裸机点亮LED灯
  5. eShopOnContainers 知多少[5]:EventBus With RabbitMQ
  6. 邻接表的两种实现(链表和数组模拟)
  7. 产品战略规划十步法ppt_从管理咨询角度谈如何系统地做产品战略规划?
  8. kafka 的安装部署
  9. JAVASCRIPT 上传文件的几种方式
  10. python读取txt数据
  11. 市场巨星的挖掘者、硅谷投资权威——早在1992年就走进星巴克办公室的Michael Moe...
  12. DirectX11,DirectX12,OpenGL,Vulkan学习资料
  13. 14、UI_02拨号盘动画
  14. Oracle卸载的全过程
  15. 《扫黑风暴》全网爆火!用Python具体分析一下它怎么火起来的?
  16. 【转】经典!python中使用xlrd、xlwt操作excel表格详解
  17. 2022-2028全球重度抑郁症治疗行业调研及趋势分析报告
  18. 正则表达式--匹配简体繁体中文姓名,还有少数民族的·号
  19. 【openjudge】开餐馆
  20. cockroachdb_CockroachDB评论:分布式SQLSwift发展

热门文章

  1. 包画三维散点图怎么导出_不开玩笑,发现宝藏了,一键导出场地三维模型,连贴图都有!...
  2. java安全接口调用_步骤3:调用Java接口
  3. ospf避免环路_OSPF路由协议的区域防环机制
  4. GetSystemMetrics()函数的用法
  5. pta l2-7(家庭房产)
  6. mysql数据库sql语句大全
  7. spring面试重点
  8. Maven系列三Maven内置变量
  9. LAMMP源码环境搭建
  10. bootloader烧写