码迷,mamicode.com
首页 > Windows程序 > 详细

C# 读取txt配置文件,并且可以更新配置文件

时间:2016-11-24 07:03:44      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:code   lower   void   adl   try   new   分享   截图   配置文件   

技术分享

 

首先,配置使用=号隔开的,等号前面是表示配置项,后面是配置的值

功能:可以读取txt配置文件和修改txt配置文件

我们可以理解成key=value的形式,上面的截图,可以说明一些,不废话了,下面上代码吧。

private static string _path_config = Application.StartupPath + "\\config.txt";  //配置文件
        private void Form1_Load(object sender, EventArgs e)
        {
            //读取配置文件
            List<string[]> config = ReadFromTxt();
            if (config != null)
            {
                try
                {
                    foreach (string[] str in config)
                    {
                        string temp = str[0];
                        switch (temp.ToLower())
                        {
                            case "host":
                                txthost.Text = str[1];
                                break;
                            case "format":
                                txtgeshi.Text = str[1];
                                break;
                        }
                    }
                }
                catch { }
            }
        }
        /// <summary>
        /// 读取TXT
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>string数组</returns>
        private List<string[]> ReadFromTxt()
        {
            try
            {

                if (!System.IO.File.Exists(_path_config))
                {
                    return null;
                }
                string line;
                List<string[]> result = new List<string[]>();
                StreamReader sr = new StreamReader(_path_config);
                while ((line = sr.ReadLine()) != null)
                {
                    result.Add(line.Split(=));
                }
                sr.Close();
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 更新配置文件
        /// </summary>
        /// <param name="host"></param>
        /// <param name="format"></param>
        private void UpdateConfig(string host, string format)
        {
            if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(format))
            {
                string[] line = new string[2];
                line[0] = "host=" + host;
                line[1] = "format=" + format;
                File.WriteAllLines(_path_config, line);
            }
        }
复制代码

 

C# 读取txt配置文件,并且可以更新配置文件

标签:code   lower   void   adl   try   new   分享   截图   配置文件   

原文地址:http://www.cnblogs.com/testsec/p/6095764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!