C#读写配置文件的代码

FileIni.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace First_Demo
{
    class FileIni
    {

        private static String WriteText(String FilePath, string data)
        {
            //String FilePath = GetDirectory() + "\\" + "MyFileSend" + GetDate() + ".txt";

            System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath, false); //文件覆盖方式添加内容

            file.Write(data); //保存数据到文件

            file.Close();  //关闭文件

            file.Dispose(); //释放对象

            return FilePath;
        }

        /// <summary>
        /// 获取文件中的数据
        /// </summary>
        /// <param name="args"></param>
        private static List<string> ReadTextToList(String filePath)
        {
            List<string> strData = new List<string>();
            try
            {
                string line;
                // using语句。
                // 定义一个范围,在范围结束时处理对象。 
                // 场景: 
                // 当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。 
                // 要达到这样的目的,用try...catch来捕捉异常也是可以的,但用using也很方便。

                // 创建一个 StreamReader 的实例来读取文件 ,using 语句也能关闭 StreamReader
                using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
                {
                    // 从文件读取并显示行,直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                        strData.Add(line);//strData = line;
                    }
                }
            }
            catch (Exception e)
            {
                // 向用户显示出错消息
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            return strData;
        }


        public class LineStruct
        {
            public string Left;
            public string Right;
        }

        static private bool IsSpaceOrTabChar(char ch)
        {
            if (ch == ' ' || ch == 0x09)return true;
            return false;
        }

        static private bool IsNameChar(char ch)
        {
            if (ch >= '0' && ch <= '9' )return true;
            else if (ch >= 'a' && ch <= 'z' )return true;
            else if (ch >= 'A' && ch <= 'Z' )return true;
            else if (ch == '_')return true;
            else if (ch == '-')return true;
            return false;
        }

        private static LineStruct AnalyseOneLine(string strin)
        {
            LineStruct ret = new LineStruct();
            int State = 0;
            for (int j = 0; j < strin.Length; j++)
            {
                char ch = strin[j];//strin.ElementAt(j);
                switch (State)
                {
                    case 0: // 一开始的空白
                        if (IsSpaceOrTabChar(ch)) { }
                        else if (IsNameChar(ch)) { ret.Left += ch; State++; }
                        else return ret;
                        break;
                    case 1: // 读左值中
                        if (IsNameChar(ch)) { ret.Left += ch; }
                        else if (ch == ':') { State += 2; }
                        else if (IsSpaceOrTabChar(ch)) { State++; }
                        else return ret;
                        break;
                    case 2: // 冒号前的空白
                        if (ch == ':') { State ++; }
                        else if (IsSpaceOrTabChar(ch)) {}
                        else return ret;
                        break;
                    case 3: // 冒号后的空白
                        if (IsSpaceOrTabChar(ch)) { State++; }
                        else if (IsNameChar(ch)) { ret.Right += ch; }
                        else return ret;
                        break;
                    case 4: // 读右值中
                        if (IsNameChar(ch)) { ret.Right += ch; }
                        else { return ret;}
                        break;
                    default: break;
                }
            }
            return ret;
        }

        static bool IsReadAll = false;
        static string ConfigFileName = "Config.ini";
        static Dictionary<string, string> ConfigBuf = new Dictionary<string, string>();
        private static void ReadAllConfig()
        {
            List<string> listdata = ReadTextToList(ConfigFileName);
            for (int i = 0; i < listdata.Count; i++)
            {
                string strTmp = listdata.ElementAt(i);

                LineStruct eleTmp = AnalyseOneLine(strTmp);

                ConfigBuf.Add(eleTmp.Left, eleTmp.Right);

            }
            IsReadAll = true;
        }

        public static string ReadConfig(String Key)
        {
            if (IsReadAll == false) ReadAllConfig();

            string data = "";
            bool res = ConfigBuf.TryGetValue(Key, out data);
            return data;
        }

        private static string Dictionary_to_string(Dictionary<string, string> dic)
        {
            if (IsReadAll == false) ReadAllConfig();

            string ret = "";
            for (int i = 0; i < dic.Count; i++ )
            {
                string tmp = dic.ElementAt(i).Key.ToString() + ":" + dic.ElementAt(i).Value.ToString();
                ret = ret + tmp + "\r\n";
            }
            
            return ret;
        }

        public static void WriteConfig(string Key, string data)
        {
            if (ConfigBuf.ContainsKey(Key) == false) ConfigBuf.Add(Key, data);
            else ConfigBuf[Key] = data;
            WriteText(ConfigFileName, Dictionary_to_string(ConfigBuf));
        }

    }
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值