|
|

首先,配置使用=号隔开的,等号前面是表示配置项,后面是配置的值
功能:可以读取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# 判断url是否为相对路径,还是绝对路径下一篇:_2016.05.16_码农网全新战略调整
|