收藏几个有用的操作xml、config、ini文件的类

一、在winCE环境下操作ini文件的类:

1、类文件ReadIniFile.cs:

using System;

using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace newProject
{
    public class ReadIniFile
    {
        /************************************************************************/
        /*写操作
         * strSection   节
         * strKey       键
         * strValue     需要写入的值
         * strFilePath  配置文件的全路径(wince中只能使用绝对全路径)
         */
        /************************************************************************/

        public static void PutINI(string strSection, string strKey, string strValue, string strFilePath)
        {
            INICommon(false, strSection, strKey, strValue, strFilePath);
        }

        /************************************************************************/
        /* 读操作
         * strSection   节
         * strKey       键
         * strDefault   如果未找到相应键对应的值则填入此值
         * strFilePath  配置文件的全路径(wince中只能使用绝对全路径)
         * 返回:       指定键的相应值
         * 说明:       如果在文件中未找到相应节则添加,未找到相应键亦添加,如果键对应的值为空串则使用默认值填充ini文件并返回
        /************************************************************************/

        public static string GetINI(string strSection, string strKey, string strDefault, string strFilePath)
        {
            return INICommon(true, strSection, strKey, strDefault, strFilePath);
        }

        private static string[] Split(string input, string pattern)
        {
            string[] arr = System.Text.RegularExpressions.Regex.Split(input, pattern);
            return arr;
        }
        private static void AppendToFile(string strPath, string strContent)
        {
            FileStream fs = new FileStream(strPath, FileMode.Append);
            StreamWriter streamWriter = new StreamWriter(fs, System.Text.Encoding.Default);
            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            streamWriter.WriteLine(strContent);
            streamWriter.Flush();
            streamWriter.Close();
            fs.Close();
        }
        private static void WriteArray(string strPath, string[] strContent)
        {
            FileStream fs = new FileStream(strPath, FileMode.Truncate);
            StreamWriter streamWriter = new StreamWriter(fs, System.Text.Encoding.Default);
            streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);

            for (int i = 0; i < strContent.Length; i++)
            {
                if (strContent[i].Trim() == "\r\n")
                    continue;
                streamWriter.WriteLine(strContent[i].Trim());
            }

            streamWriter.Flush();
            streamWriter.Close();
            fs.Close();
        }
        //INI解析
        private static string INICommon(bool isRead, string ApplicationName, string KeyName, string Default, string FileName)
        {
            string strSection = "[" + ApplicationName + "]";
            string strBuf;
            try
            {
                //a.文件不存在则创建
                if (!File.Exists(FileName))
                {
                    FileStream sr = File.Create(FileName);
                    sr.Close();
                }
                //读取INI文件
                System.IO.StreamReader stream = new System.IO.StreamReader(FileName, System.Text.Encoding.Default);
                strBuf = stream.ReadToEnd();//读取ini文件
                stream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "INI文件读取异常");
                return Default;
            }

            string[] rows = Split(strBuf, "\r\n");
            string oneRow;
            int i = 0;
            for (; i < rows.Length; i++)
            {
                oneRow = rows[i].Trim();

                //空行
                if (0 == oneRow.Length)
                    continue;

                //此行为注释
                if (';' == oneRow[0])
                    continue;

                //没找到
                if (strSection != oneRow)
                    continue;

                //找到了
                break;
            }

            //b.没找到对应的section,创建一节并创建属性
            if (i >= rows.Length)
            {
                AppendToFile(FileName, "\r\n" + strSection + "\r\n" + KeyName + "=" + Default);
                return Default;
            }

            //找到section

            i += 1; //跳过section 

            int bakIdxSection = i;//备份section的下一行

            string[] strLeft;

            //查找属性
            for (; i < rows.Length; i++)
            {
                oneRow = rows[i].Trim();

                //空行
                if (0 == oneRow.Length)
                    continue;

                //此行为注释
                if (';' == oneRow[0])
                    continue;

                //越界
                if ('[' == oneRow[0])
                    break;

                strLeft = Split(oneRow, "=");

                if (strLeft == null || strLeft.Length != 2)
                    continue;

                //找到属性
                if (strLeft[0].Trim() == KeyName)
                {
                    //读
                    if (isRead)
                    {
                        //c.找到属性但没有值
                        if (0 == strLeft[1].Trim().Length)
                        {
                            rows[i] = strLeft[0].Trim() + "=" + Default;
                            WriteArray(FileName, rows);
                            return Default;
                        }
                        else
                        {
                            //找到了                        
                            return strLeft[1].Trim();
                        }
                    }

                    //写
                    else
                    {
                        rows[i] = strLeft[0].Trim() + "=" + Default;
                        WriteArray(FileName, rows);
                        return Default;
                    }
                }
            }

            //d.没找到对应的属性,创建之并赋为默认
            rows[bakIdxSection] = rows[bakIdxSection] + "\r\n" + KeyName + "=" + Default;
            WriteArray(FileName, rows);
            return Default;
        }


    }
}

2、后台调用:
读取ini文件:

string mailto:IniPath=@%22E://a.ini"

 private void read_Click(object sender, EventArgs e)
        {

         string text=ReadIniFile.GetINI("aa", "bb", "", IniPath);

}

写入ini文件

private void write_Click(object sender, EventArgs e)
        {

           ReadIniFile.PutINI("aa", "bb", "cc", IniPath);

}

 

二、在windows环境下操作ini文件

1、类文件ReadIniFile.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public class ReadIniFile
    {
        public string fileName;
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(
           string lpAppName,// 指向包含 Section 名称的字符串地址 
           string lpKeyName,// 指向包含 Key 名称的字符串地址 
           string lpDefault,// 如果 Key 值没有找到,则返回缺省的字符串的地址 
           StringBuilder lpReturnedString,// 返回字符串的缓冲区地址 
           int nSize,// 缓冲区的长度 
           string lpFileName
           );

        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(
        string lpAppName,
        string lpKeyName,
        string lpString,
        string lpFileName
        );

        public ReadIniFile(string filename)
        {
            this.fileName = filename;

        }
        public string GetString(string section, string key)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(section, key, "", temp, 1024, this.fileName);
            return temp.ToString();

        }

        public bool ExistINIFile()
        {
            return File.Exists(this.fileName);
        }
        public string FileName()
        {
            return this.fileName;
        }
        public void WriteInt(string section, string key, int iVal)
        {
            WritePrivateProfileString(section, key, iVal.ToString(), fileName);
        }
        public void WriteString(string section, string key, string strVal)
        {
            WritePrivateProfileString(section, key, strVal, fileName);
        }

        public void DelKey(string section, string key)
        {
            WritePrivateProfileString(section, key, null, fileName);
        }
        public void DelSection(string section)
        {
            WritePrivateProfileString(section, null, null, fileName);
        }


    }
}

 

2、后台调用方法

private void bWIni_Click(object sender, EventArgs e)
        {
            string a = mark.Text;
            string b = WrIni.Text;
            writefile(a,b);
        }

        private void bRIni_Click(object sender, EventArgs e)
        {
            ReIni.Text = readfile();
        }

 

三、操作XML文件

类文件ReXML.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// XML操作类,包含XML的常用操作
    /// </summary>
    public class ReXML
    {
        protected XmlDocument xdoc = new XmlDocument();
        public XmlElement root;

        public ReXML()
        { 
        
        }

        /// <summary>
        /// 加载XML文件
        /// </summary>
        /// <param name="xmlText">传入文档名称</param>
        public void LoadXml(string xmlText)
        {
            XmlReader reader = new XmlTextReader(xmlText);
            xdoc.Load(reader);
            root = (XmlElement)xdoc.FirstChild;
        }


        /// <summary>
        /// 取得名为name的结点值
        /// </summary>
        /// <param name="name">指定的结点名</param>
        /// <returns>返回结点值</returns>
        public string GetValue(string name)
        {
            XmlNode xn = FindXnByName(root.ChildNodes, name);
            if (xn == null)
                return null;
            return xn.InnerText;
        }

        /// <summary>
        /// 通过节点名称找到指定的节点
        /// </summary>
        /// <param name="xnl">排序的结点集合</param>
        /// <param name="strName">指定的节点名称</param>
        /// <returns>返回指定的节点</returns>
        public XmlNode FindXnByName(XmlNodeList xnl, string strName)
        {
            for (int i = 0; i < xnl.Count; i++)
            {
                if (xnl.Item(i).LocalName == strName)
                    return xnl.Item(i);
            }
            return null;
        }

        /// <summary>
        /// 找到指定名称属性的值
        /// </summary>
        /// <param name="xac">属性集合</param>
        /// <param name="strName">指定的属性名称</param>
        /// <returns>属性的值</returns>
        public string GetXaValue(XmlAttributeCollection xac, string strName)
        {
            for (int i = 0; i < xac.Count; i++)
            {
                if (xac.Item(i).LocalName == strName)
                    return xac.Item(i).Value;
            }
            return null;
        }

        /// <summary>
        /// 找到指定名称属性的值
        /// </summary>
        /// <param name="xnl">排序的结点集合</param>
        /// <param name="strName">指定的属性名称</param>
        /// <returns>属性的值</returns>
        public string GetXnValue(XmlNodeList xnl, string strName)
        {
            for (int i = 0; i < xnl.Count; i++)
            {
                if (xnl.Item(i).LocalName == strName)
                    return xnl.Item(i).InnerText;
            }
            return null;
        }

        /// <summary>
        /// 寻找具有指定名称和属性/值组合的结点
        /// </summary>
        /// <param name="xn">排序的结点集合</param>
        /// <param name="strXaName">指定的属性名称</param>
        /// <param name="strXaValue">指定的属性值</param>
        /// <returns></returns>
        public XmlNode FindXnByXa(XmlNodeList xn, string strXaName, string strXaValue)
        {
            string xa;
            for (int i = 0; i < xn.Count; i++)
            {
                xa = GetXaValue(xn.Item(i).Attributes, strXaName);
                if (xa != null)
                {
                    if (xa == strXaName)
                        return xn.Item(i);
                }
            }
            return null;
        }
    }
}


四、操作app.config文件

类名称ReConfig:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Configuration;

namespace WindowsFormsApplication1
{
    public class ReConfig
    {
        /// <summary>
        /// 读取App.confign配置信息
        /// </summary>
        /// <param name="AppKey">节点</param>
        /// <returns>返回KeyValue</returns>
        public static string ReadConfigInfo(string AppKey)
        {
            string AppKeyValue;
            AppKeyValue = System.Configuration.ConfigurationManager.AppSettings.Get(AppKey);
            return AppKeyValue;
        }

        /// <summary>
        /// 写入App.config配置信息
        /// </summary>
        /// <param name="AppKey">节点</param>
        /// <param name="AppValue">值</param>
        public static void WriterConfigInfo(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值