您的位置:首页 > 其它

自己写的 读写 ini 配置文件类

2015-08-04 10:01 239 查看
/// <summary>
/// 不调用系统API 读写 ini 配置文件
/// </summary>
public class RW_ini
{
#region ========ini 读写========
// 首次调用 RWini 时需要初始化此参数
public static string pathIni;
// 记录错误信息 与 WriteLog 一起使用
public static string pathErr;

public static string ReadIni(string section, string key)
{
string result = "";
try
{
// 文件存在
if (File.Exists(pathIni))
{
//读取INI文件
string buffer;
string[] temp;
using (StreamReader sr = new StreamReader(pathIni, Encoding.Default))
{
while (sr.Peek() >= 0)
{
buffer = sr.ReadLine().Trim();
if (!string.IsNullOrEmpty(buffer) && buffer.StartsWith(string.Format("[{0}]", section), StringComparison.OrdinalIgnoreCase))
{
while (sr.Peek() > 0)
{
buffer = sr.ReadLine().Trim();
if (!string.IsNullOrEmpty(buffer))
{
if (buffer.StartsWith("["))
break;
if (!buffer.StartsWith(";"))
{
temp = buffer.Split('=');
if (temp.Length > 1 && temp[0].TrimEnd().Equals(key, StringComparison.OrdinalIgnoreCase))
{
return temp[1].TrimStart();
}
}
}
}
// 不再判断下一个节点
return result;
}
}
}
}
// 不再判断下一个节点
return result;
}
catch
{
throw new ApplicationException("同步文件读取异常!");
}
}

private void WriteIni(string section, string key, string value)
{
try
{
// 文件不存在则创建
if (!File.Exists(pathIni))
{
File.Create(pathIni);
}
// 修改INI文件
bool modify = false, find = false;
string buffer;
List<string> temp = new List<string>();
// 将所有配置文件放到集合中
using (StreamReader sr = new StreamReader(pathIni, Encoding.Default))
{
while (sr.Peek() >= 0)
{
buffer = sr.ReadLine().Trim();
temp.Add(buffer);

if (!modify && !string.IsNullOrEmpty(buffer) && buffer.StartsWith(string.Format("[{0}]", section), StringComparison.OrdinalIgnoreCase))
{
find = true;
while (sr.Peek() >= 0)
{
buffer = sr.ReadLine().Trim();
temp.Add(buffer);
if (!string.IsNullOrEmpty(buffer))
{
if (buffer.StartsWith("["))
break;
if (!modify && !buffer.StartsWith(";") && buffer.Split('=')[0].TrimEnd() == key)
{
modify = true;
temp.RemoveAt(temp.Count - 1);
if (value != null)
{
temp.Add(string.Format("{0} = {1}", key, value));
}
}
}
}

if (!modify)
{
temp.Insert(temp.Count - 1, string.Format("{0} = {1}", key, value));
}
}
}
if (!modify && !find)
{
temp.Add(string.Format("[{0}]", section));
temp.Add(string.Format("{0} = {1}", key, value));
}
}
using (StreamWriter sw = new StreamWriter(pathIni, false, Encoding.Default))
{
foreach (string item in temp)
sw.WriteLine(item);
}
}
catch
{
throw new ApplicationException("同步文件写入异常!");
}
}

public static void WriteLog(string content)
{
File.AppendText(pathErr).WriteLine("时间:{0} 信息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), content);
}
}


因为 WinCE 不带读写 ini 的API 而且自己用的配置文件节点并不多

因此自己编写此类 用于 WinCE 系统中。C# 代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: