黑马程序员技术交流社区
标题:
用正则表达式读取INI文件
[打印本页]
作者:
aisini
时间:
2014-8-20 14:37
标题:
用正则表达式读取INI文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace INIFileHandler
{
/// <summary>
/// INI文件类
/// </summary>
public class INIFile
{
const string regexSection = "\\[[\\w\\s]*\\][^\\[]*";
const string regexSectionTitle = "^\\[([\\w\\s]*\\])$";
const string regexKeyValue = "^(\\w*\\s*)=(\\s*\\w*)$";
const string regexCommon = "^;.*$";
public string filepath; //载入的文件内容。
public string content; //以字符串的行保存载入文件的所有内容。
public List<Section> profileSections
public INIFile()
{
this.filepath = "";
this.content = "";
}
public INIFile(string filepath)
{
try
{
if (!File.Exists(filepath)) return;
this.filepath = filepath;
}
catch (Exception ex)
{ }
}
public void Load(string filepath)
{
try
{ content = filereader(filepath, Encoding.Default); }
catch (Exception)
{ return; }
foreach (Match section in Regex.Matches(content, regexSection))
{
Section newSection = new Section();
newSection.sectionTitle = Regex.Replace(Regex.Match(section.ToString(), regexSectionTitle).ToString(), regexSectionTitle, "$1").ToString().Trim();
foreach (Match keyvalue in Regex.Matches(section.ToString(), regexKeyValue))
{
newSection.addKeyValue(new KeyValue(Regex.Replace(keyvalue.ToString(), regexKeyValue, "$1").ToString(), Regex.Replace(keyvalue.ToString(), regexKeyValue, "$2").ToString()));
}
this.profileSections.Add(newSection);
}
}
/// <summary>
/// 文件读入
/// </summary>
/// <param name="filename">文件名</param>
/// <param name="encoding">编码</param>
/// <returns>读入的文本内容</returns>
public string filereader(string filename, Encoding enc)
{
return "";
}
/// <summary>
/// 写入修改
/// </summary>
/// <param name="filename">文件名</param>
/// <param name="encoding">编码</param>
public void filewriter(string filename, Encoding enc)
{
}
}
public class KeyValue
{
public string KeyName;
public string KeyValue;
public KeyValue()
{
KeyName = "";
KeyValue = "";
}
public KeyValue(string KeyName, string KeyValue)
{
this.KeyName = KeyName;
this.KeyValue = KeyValue;
}
}
public class Section
{
public string sectionTitle;
public List<KeyValue> keyValues;
int Count;
public Section(string title, List<KeyValue> keyValues)
{
this.sectionTitle = title;
this.keyValues = keyValues;
this.Count = keyValues.Count;
}
public Section()
{
sectionTitle = "";
this.Count = 0;
keyValues = new List<KeyValue>() { };
}
/// <summary>
/// 添加键值对
/// </summary>
/// <param name="kv">KeyValue对象</param>
public void addKeyValue(KeyValue kv)
{
keyValues.Add(kv);
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2