30
2012
03

C# INI配置文件操作类库

文章以及代码的版权说明:
本文为原创文章,文章可以自由转载,但请注明出处。
本文所涉及的代码可以任意使用,作者不会为他人的使用承担任何责任。

==========================================
虽然XML的功能很强大,但是INI文件仍然可以起一定的作用,因为文件简洁,而且占空间相比之下少。
由于C#没有直接提供INI文件的操作类库,所以自己动手写了一个。
基本是用一个Dictionary嵌套来存放节以及键的数据的。
功能不是很完善,读者可以自己添加。

==========================================
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace INISupport
{
/// <summary>
/// 定义了键值、节修改的标志
/// </summary>
public enum UpdateFlags
{
CreateAll,
OnlyCreateKey,
OnlyUpdate
}

/// <summary>
/// 本类实现对INI文件的读写操作
/// </summary>
public class INIReader
{
// INI文件数据,两层字典嵌套,便于组织以及查找
// 第一层为Section(节)
// 第二层即为该Section的数据,Key = Value
private Dictionary<string, Dictionary<string, string>> _INIData;

/// <summary>
/// 创建空的INI文件
/// </summary>
public INIReader()
{
_INIData = new Dictionary<string, Dictionary<string, string>>();
}
/// <summary>
/// 由文件创建INI文件
/// </summary>
/// <param name="FileName">文件名</param>
/// <param name="EncodingValue">文件编码</param>
public INIReader(string FileName,Encoding EncodingValue)
{
// 临时存放INI文件的文件流
StreamReader _iniStream = new StreamReader(FileName, EncodingValue);

// 初始化流
_iniStream.BaseStream.Seek(0, SeekOrigin.Begin);

// 初始化INIDATA
_INIData = new Dictionary<string, Dictionary<string, string>>();

// 一行一行遍历ini
string LineText = ""; // 行文本
string SectionName = ""; // 节名称
Dictionary<string, string> Section = new Dictionary<string,string>(); // 节
LineText = _iniStream.ReadLine();
LineText = LineText.Trim(); // 剔除空白字符
while (_iniStream.EndOfStream == false)
{
// 分析部分
// 删除注释
int _a = LineText.IndexOf(';');
if (_a != -1) { LineText = LineText.Remove(_a, LineText.Length - _a); } // 以”;“开头的部分 
int _b = LineText.IndexOf("//");
if (_b != -1) { LineText = LineText.Remove(_b, LineText.Length - _b); } // 以”//“开头的部分
LineText = LineText.Trim(); // 剔除空白字符

// 跳过空行
if (LineText == "")
{
// 再读取
LineText = _iniStream.ReadLine();
LineText = LineText.Trim(); // 剔除空白字符
continue;
}

// 存在一对”[]“即为项
_a = LineText.IndexOf('[');
_b = LineText.IndexOf(']');
if ((_a != -1) && (_b != -1))
{
LineText = LineText.Remove(_a, _a+1);
_b = LineText.IndexOf(']'); // 更新位置
LineText = LineText.Remove(_b, LineText.Length - _b);

// 如果有旧数据,加入 _INIData
if (Section.Count > 0) { _INIData.Add(SectionName, Section); }
// 新建section
SectionName = LineText;
Section = new Dictionary<string, string>();

// 再读取
LineText = _iniStream.ReadLine();
LineText = LineText.Trim(); // 剔除空白字符
continue;
}

// 存在等于号,即为子项
_a = LineText.IndexOf('=');
if (_a != -1)
{
// 直接分割成两部分
string[] temp = LineText.Split(new[] {'='},2);

// 添加处理
// 如果存在相同键值
if (Section.ContainsKey(temp[0]))
{
Section[temp[0]] = temp[1];
}
else
{
Section.Add(temp[0], temp[1]);
}
}

// 再读取
LineText = _iniStream.ReadLine();
LineText = LineText.Trim(); // 剔除空白字符
}
// 最后一组,如果有旧数据,加入 _INIData
if (Section.Count > 0) { _INIData.Add(SectionName, Section); }

// 关闭流
_iniStream.Close();
}

// ***** 操作实现 ***** //
// *** 读取键值 *** //
/// <summary>
/// 读取键值
/// </summary>
/// <param name="Section">节</param>
/// <param name="Key">键名称</param>
/// <returns>返回键值</returns>
public string GetValue(string Section, string Key)
{
string retValue = "";

try
{
retValue = (_INIData[Section])[Key];
}
catch
{
retValue = "";
}

return retValue;
}
/// <summary>
/// 读取键值
/// </summary>
/// <param name="Section">节</param>
/// <param name="Key">键名称</param>
/// <param name="Default">默认值</param>
/// <returns>返回键值</returns>
public string GetValue(string Section, string Key,string Default)
{
string retValue = "";

try
{
retValue = (_INIData[Section])[Key];
}
catch
{
retValue = Default;
}

return retValue;
}

// *** 修改键值 *** //
/// <summary>
/// 更新键值
/// </summary>
/// <param name="Section">节</param>
/// <param name="Key">键名称</param>
/// <param name="Value">修改值</param>
/// <param name="Flags">更新标志</param>
/// <returns>返回真则更新成功,否则假</returns>
public bool UpdateValue(string Section, string Key, string Value, UpdateFlags Flags)
{
if (_INIData.ContainsKey(Section)) // 如果存在节点
{
if (_INIData[Section].ContainsKey(Key)) // 存在键值
{
if (Flags != UpdateFlags.OnlyCreateKey) // 检查标志
{
(_INIData[Section])[Key] = Value;
}
else // 不允许修改键值
{
return false;
}
}
else
{
if ((Flags == UpdateFlags.OnlyCreateKey) || (Flags == UpdateFlags.CreateAll)) // 允许创建键值
{
(_INIData[Section]).Add(Key, Value);
}
else
{
return false;
}
}
}
else
{
if (Flags == UpdateFlags.CreateAll)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
temp.Add(Key, Value);
_INIData.Add(Section, temp);
}
else
{
return false;
}
}
return true;
}

// *** 删除键值 *** //
/// <summary>
/// 删除键值
/// </summary>
/// <param name="Section">节名称</param>
/// <param name="Key">键值</param>
/// <returns>返回是否成功</returns>
public bool DeleteKey(string Section, string Key)
{
bool ret = false;
try
{
_INIData[Section].Remove(Key);
ret = true;
}
catch
{
ret = false;
}

return ret;
}
/// <summary>
/// 删除节
/// </summary>
/// <param name="Section">节名称</param>
/// <returns>返回是否成功</returns>
public bool DeleteSection(string Section)
{
bool ret = false;
try
{
_INIData.Remove(Section);
ret = true;
}
catch
{
ret = false;
}

return ret;
}

// *** 判断值 *** //
/// <summary>
/// 是否存在节
/// </summary>
/// <param name="Section">节名称</param>
/// <returns>返回逻辑值</returns>
public bool SectionExisted(string Section)
{
return _INIData.ContainsKey(Section);
}
/// <summary>
/// 是否存在键
/// </summary>
/// <param name="Section">节名称</param>
/// <param name="Section">键名称</param>
/// <returns>返回逻辑值</returns>
public bool KeyExisted(string Section,string Key)
{
bool ret = false;
try
{
ret = (_INIData[Section]).ContainsKey(Key);
}
catch
{
ret = false;
}

return ret;
}

// ***** 保存 ***** //
/// <summary>
/// 输出为string
/// </summary>
/// <returns>输出的字符串</returns>
public string Save()
{
string ret = "";

foreach(KeyValuePair<string,Dictionary<string,string>> ta in this._INIData)
{
ret = ret + "[" + ta.Key + "]" + "\n";
foreach (KeyValuePair<string, string> tb in ta.Value)
{
ret = ret + tb.Key + "=" + tb.Value + "\n";
}
}

return ret;
}
/// <summary>
/// 保存到文件
/// </summary>
/// <param name="FileName">文件名</param>
public void SaveTo(string FileName)
{
FileStream file = new FileStream(FileName, FileMode.Create);
file.Seek(0, SeekOrigin.Begin);
byte[] strbuffer = System.Text.Encoding.Default.GetBytes(this.Save());
file.Write(strbuffer, 0, strbuffer.Length);
}
}
}

转载:http://hi.baidu.com/823904362/blog/item/d49f9df1162a4e07b17ec554.html

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。