仿Ini文件的读写

来源:互联网 发布:shadowsock for mac 编辑:程序博客网 时间:2024/06/05 08:15
//因为在WinCe平台上开发软件,但是WinCe平台不支持Ini功能,所以就自己写了一个!using System.Collections.Generic;using System.IO;using System.Text;using System;namespace myIniJQ{    /// <summary>    /// 创建ini格式的txt文档    /// </summary>    public class winEcIniJQ    {        private string Path;        /// <summary>        ///  初始化winEc文件读写函数        /// </summary>        /// <param name="Path"></param>        public winEcIniJQ(string Path)        {            Path = Path.Replace("file:\\", "");            this.Path = Path;        }        /// <summary>        /// 读取保存(因为偶尔会出现莫名错误,所以先读取一遍,然后再按照utf-8的格式保存下来,确保文件万无一失)        /// </summary>        /// <returns></returns>        private bool WinNewRead()        {            bool FileState = false;            string strRead = "";            Path = Path.Replace("file:\\", "");            try            {                if (File.Exists(Path))                {                    List<string> addstrlist = new List<string>();                    StreamReader streamread = new StreamReader(Path, Encoding.UTF8);//打开文件                    while ((strRead = streamread.ReadLine()) != null)                    {                        if (strRead != "")                        {                            addstrlist.Add(strRead);                        }                    }                    streamread.Close();                    StrFlush(addstrlist);                    FileState = true;                }                return FileState;            }            catch (Exception ex)            {                FileState = false;                //记录异常                string startError = "winEcIniJQ.WinNewRead函数异常发生时间:" + DateTime.Now.ToString("HHmmss") + " " + ex.InnerException.ToString();                //因为无法预知的异常,并且在出现异常的时候显控无法在窗体上提示,所以我们要创建一个异常文件,来记录当前发生的异常;                string Errorurl = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\winEcIniJQError.txt";                Errorurl = Errorurl.Replace("file:\\", "");                StreamWriter stream = new StreamWriter(Errorurl, true);                stream.WriteLine(startError);                stream.Flush();                stream.Close();                return FileState;            }        }        /// <summary>        /// 读取ini格式的文件        /// </summary>        /// <param name="HeadName">文件头索引</param>        /// <param name="Body">文件内容索引</param>        /// <param name="End">文件内容</param>        /// <returns></returns>        public string WinEcRead(string HeadName, string Body, string End)        {            string Read = "";            string strRead = "";            Path = Path.Replace("file:\\", "");            try            {                if (File.Exists(Path) && WinNewRead())                {                    List<string> addstrlist = new List<string>();                    StreamReader streamread = new StreamReader(Path, Encoding.UTF8);//打开文件                    while ((strRead = streamread.ReadLine()) != null)                    {                        if (strRead != "")                        {                            addstrlist.Add(strRead);                        }                    }                    streamread.Close();                    int begin = 0;                    int Colos = 0;                    for (int i = 0; i < addstrlist.Count; i++)                    {                        //找出数据当中的汉字,因为汉字用[]括起来,所以直接查找[ \ ]即可.                        if (addstrlist[i].Contains("["))                        {                            //确定当前索引头的位置                            begin = addstrlist.IndexOf(HeadName);                            if (begin < i)                            {                                Colos = i; //找出当前数据头最近的一个数据头                                continue;                            }                        }                    }                    if (Colos == 0) { Colos = addstrlist.Count; }                    if (addstrlist.Contains(HeadName))                    {                        for (int j = begin; j < Colos; j++)                        {                            //因为会有很多近似相同的数据,所以要作出更精确的判断                            int dataindex = addstrlist[j].IndexOf(":");                            if (addstrlist[j].Contains(Body))                            {                                string newBody = addstrlist[j].Substring(0, dataindex);                                if (newBody.Equals(Body))                                {                                    Read = addstrlist[j];                                    Read = Read.Substring(Body.Length + 2, Read.Length - (Body.Length + 2));                                    break;                                }                            }                            else if (!addstrlist[j].Contains(Body))                            {                                continue;  //相当于换行                            }                        }                    }                }                return Read;            }            catch (Exception ex)            {                //记录异常                string startError = "winEcIniJQ.WinEcRead函数异常发生时间:" + DateTime.Now.ToString("HHmmss") + " " + ex.InnerException.ToString();                //因为无法预知的异常,并且在出现异常的时候显控无法在窗体上提示,所以我们要创建一个异常文件,来记录当前发生的异常;                string Errorurl = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\winEcIniJQError.txt";                Errorurl = Errorurl.Replace("file:\\", "");                StreamWriter stream = new StreamWriter(Errorurl, true);                stream.WriteLine(startError);                stream.Flush();                stream.Close();            }            return Read;        }        /// <summary>        ///  写入ini格式的txt文件        /// </summary>        /// <param name="HeadName">文件头索引</param>        /// <param name="Body">文件内容索引</param>        /// <param name="End">文件内容</param>        public void WinEcWrite(string HeadName, string Body, string End)        {            string strRead = "";            Path = Path.Replace("file:\\", "");            //判断文件存在则要在指定的位置写入数据            try            {                if (File.Exists(Path) && WinNewRead())                {                    StreamReader read = new StreamReader(Path, Encoding.UTF8);//打开文件                    List<string> addstrlist = new List<string>();                    while ((strRead = read.ReadLine()) != null)                    {                        if (strRead != "")                        {                            addstrlist.Add(strRead);                        }                    }                    read.Close();                    int begin = 0;                    int Colos = 0;                    for (int i = 0; i < addstrlist.Count; i++)                    {                        //找出数据当中的汉字,因为汉字用[]括起来,所以直接查找[ \ ]即可.                        if (addstrlist[i].Contains("["))                        {                            //确定当前索引头的位置                            begin = addstrlist.IndexOf(HeadName);                            if (begin < i)                            {                                Colos = i; //找出当前数据头最近的一个数据头                                break;                            }                        }                    }                    //添加新的数据                    if (Colos == 0)                    {                        if (addstrlist.Contains(HeadName))                        {                            for (int j = begin; j < addstrlist.Count; j++)                            {                                int dataindex = addstrlist[j].IndexOf(":");                                if (addstrlist[j].Contains(Body))                                {                                    string newBody = addstrlist[j].Substring(0, dataindex);                                    if (newBody.Equals(Body))                                    {                                        addstrlist.Insert(j, Body + ":=" + End);                                        addstrlist.RemoveAt(j + 1);                                        StrFlush(addstrlist);                                        return;                                    }                                }                                else if (!addstrlist[j].Equals(Body))                                {                                    continue;  //相当于换行                                }                            }                            if (!addstrlist[addstrlist.Count - 1].Equals(Body))                            {                                addstrlist.Insert(addstrlist.Count - 1, Body + ":=" + End);                                StrFlush(addstrlist);                                return;                            }                        }                        else                        {                            addstrlist.Add(HeadName);                            addstrlist.Add(Body + ":=" + End);                            StrFlush(addstrlist);                            return;                        }                    }                    //修改旧数据                    if (addstrlist.Contains(HeadName))                    {                        for (int j = begin; j < Colos; j++)                        {                            int dataindex = addstrlist[j].IndexOf(":");                            //有相同的数据  此处需要更精准的判断否则将会造成 270和70冲突                            if (addstrlist[j].Contains(Body))                            {                                string newBody = addstrlist[j].Substring(0, dataindex);                                if (newBody.Equals(Body))                                {                                    addstrlist.Insert(j, Body + ":=" + End);                                    addstrlist.RemoveAt(j + 1);                                    StrFlush(addstrlist);                                    return;                                }                            }                            else if (!addstrlist[j].Equals(Body))                            {                                continue;  //相当于换行                            }                        }                        if (!addstrlist[Colos].Equals(Body))                        {                            addstrlist.Insert(Colos, Body + ":=" + End);                            StrFlush(addstrlist);                            return;                        }                    }                    else                    {                        addstrlist.Add(HeadName);                        addstrlist.Add(Body + ":=" + End);                        StrFlush(addstrlist);                    }                }                else                {                    StreamWriter sw = new StreamWriter(Path);                    StringBuilder strbuilder = new StringBuilder();                    strbuilder.AppendLine(HeadName + "\r\n" + Body + ":=" + End);                    sw.WriteLine(strbuilder);                    sw.Flush();                    sw.Close();                }            }            catch (IOException ex)            {                //记录异常                string startError = "winEcIniJQ.WinEcWrite函数异常发生时间:" + DateTime.Now.ToString("HHmmss") + " " + ex.InnerException.ToString();                //因为无法预知的异常,并且在出现异常的时候显控无法在窗体上提示,所以我们要创建一个异常文件,来记录当前发生的异常;                string Errorurl = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\winEcIniJQError.txt";                Errorurl = Errorurl.Replace("file:\\", "");                StreamWriter stream = new StreamWriter(Errorurl, true);                stream.WriteLine(startError);                stream.Flush();                stream.Close();            }        }        /// <summary>        /// 写入数据        /// </summary>        /// <param name="addstrlist"></param>        private void StrFlush(List<string> addstrlist)        {            try            {                StreamWriter sw = new StreamWriter(Path, false, Encoding.UTF8);                foreach (string item in addstrlist)                {                    sw.WriteLine(item);                    sw.Flush();                }                sw.Close();            }            catch (IOException ex)            {                //记录异常                string startError = "winEcIniJQ.StrFlush函数异常发生时间:" + DateTime.Now.ToString("HHmmss") + " " + ex.InnerException.ToString();                //因为无法预知的异常,并且在出现异常的时候显控无法在窗体上提示,所以我们要创建一个异常文件,来记录当前发生的异常;                string Errorurl = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\winEcIniJQError.txt";                Errorurl = Errorurl.Replace("file:\\", "");                StreamWriter stream = new StreamWriter(Errorurl, true);                stream.WriteLine(startError);                stream.Flush();                stream.Close();            }        }    }}