c# ini(配置文件)文件读写(简单类)

//本文列出了ini类,不考虑节(section)。

//所谓ini文件是扩展名为ini的文本文件,常用于保存和读取配置文件。

//如下所示:

//user=JackMa

//password=123456

//在等号的左边是key,右边是value,一个对应一个value.

//本文中的value是字符串,不涉及类型转换。

//在ini类后面演示了如何使用该类。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.IO;

using System.Collections;

//namespace WindowsFormsApp1//根据情况修改命名空间,最好单独文件保存,再去掉前面的//

{

public class Config

{

public Dictionary<string, string> configData;

string fullFileName;

public Config(string _fileName)//注意路径

{

configData = new Dictionary<string, string>();

fullFileName = Application.StartupPath + @"\" + _fileName;

bool hasCfgFile = File.Exists(Application.StartupPath + @"\" + _fileName);

if (hasCfgFile == false)

{

StreamWriter writer = new StreamWriter(File.Create(Application.StartupPath + @"\" + _fileName), Encoding.Default);

writer.Close();

}

StreamReader reader = new StreamReader(Application.StartupPath + @"\" + _fileName, Encoding.Default);

string line;

int indx = 0;

while ((line = reader.ReadLine()) != null)

{

if (line.StartsWith(";") || string.IsNullOrEmpty(line))

configData.Add(";" + indx++, line);

else

{

string[] key_value = line.Split('=');

if (key_value.Length >= 2)

configData.Add(key_value[0], key_value[1]);

else

configData.Add(";" + indx++, line);

}

}

reader.Close();

}

public string get(string key)

{

if (configData.Count <= 0)

return null;

else if (configData.ContainsKey(key))

return configData[key].ToString();

else

return null;

}

public void set(string key, string value)

{

if (configData.ContainsKey(key))

configData[key] = value;

else

configData.Add(key, value);

}

public void save()

{

StreamWriter writer = new StreamWriter(fullFileName, false, Encoding.Default);

IDictionaryEnumerator enu = configData.GetEnumerator();

while (enu.MoveNext())

{

if (enu.Key.ToString().StartsWith(";"))

writer.WriteLine(enu.Value);

else

writer.WriteLine(enu.Key + "=" + enu.Value);

}

writer.Close();

}

}

}

//用法

//

// private void button_save_Click(object sender, EventArgs e)//保存

// {

// Config config = new Config("配置文件");

// if (textBox_username.Text!=null )

// { config.set("username", textBox_username.Text); }

// if (textBox_password.Text != null)

// { config.set("passowrd", textBox_password.Text); }

// config.save();

// }

// private void button_read_Click(object sender, EventArgs e)//读取

// {

// Config config = new Config("配置文件");

// textBox_username.Text= config.get("username");

// textBox_password.Text = config.get("passowrd");

// }