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));
}
}
}