65.9K
CodeProject 正在变化。 阅读更多。
Home

无 API 的 INI 文件包装器

starIconstarIconstarIconstarIconstarIcon

5.00/5 (22投票s)

2008年11月5日

CPOL
viewsIcon

84710

downloadIcon

1407

无需使用 Windows API,即可读取、写入和保存 INI 文件。

引言

使用 Windows API(WritePrivateProfileStringGetPrivateProfileString)读取和写入 INI 文件很容易,但如果您的应用程序需要多次获取或写入数据,这可能会导致性能问题,因为这些函数会在每次调用时加载 INI 文件。

因此,这个类将帮助您在内存中管理 ini 数据。

背景

这个类不使用经典的 INI 获取或放置方法。它在初始化时加载一个 INI 文件,使用正则表达式解析数据,并使用字典来管理节名称和数据。

正则表达式

static readonly Regex regRemoveEmptyLines =
    new Regex
    (
        @"(\s*;[\d\D]*?\r?\n)+|\r?\n(\s*\r?\n)*", 
        RegexOptions.Multiline | RegexOptions.Compiled
    );

static readonly Regex regParseIniData =
    new Regex
    (
        @"
        (?<IsSection>
            ^\s*\[(?<SectionName>[^\]]+)?\]\s*$
        )
        |
        (?<IsKeyValue>
            ^\s*(?<Key>[^(\s*\=\s*)]+)?\s*\=\s*(?<Value>[\d\D]*)$
        )",
        RegexOptions.Compiled | 
        RegexOptions.IgnoreCase | 
        RegexOptions.IgnorePatternWhitespace
    );

Dictionary 类型

Dictionary<string, NameValueCollection> data = 
    new Dictionary<string,NameValueCollection>();

实际上,我没有花太多时间去搜索是否已经存在类似的东西。我需要它,所以我写了它。而且,我认为有人可能会觉得这个有用。

使用代码

初始化

//Creates an empty ini document, you can add sections,
//keys and values dynamically. And you can save it anytime.
TA_INIDocument ini = new TA_INIDocument();

//Initializes an ini file, you can change its data and save
//it anytime
TA_INIDocument ini = new TA_INIDocument("C:\\sample.ini");

//Initializes an ini file with encoding. Sometimes ini files
//could have unicode data
TA_INIDocument ini = 
    new TA_INIDocument("C:\\sample.ini", Encoding.Unicode);

//Initializes ini data from stream
Stream iniStream;
TA_INIDocument ini = new TA_INIDocument(iniStream);

//Initializes ini data from stream with encoding
Stream iniStream;
TA_INIDocument ini =
    new TA_INIDocument(iniStream, Encoding.Unicode);

获取和设置值

TA_INIDocument iniDoc;

//Getting key_value collection of defined section
NameValueCollection keysAndValues = iniDoc["sectionName"];
//Getting string value of defined key and section
string value = iniDoc["sectionName"]["keyName"];
string value = iniDoc["sectionName", "keyName"];
//Setting string value of defined key
iniDoc["sectionName"]["keyName"] = "newValue";
iniDoc["sectionName", "keyName"] = "newValue";
//Getting and Setting object value of defined key and section
object value = iniDoc["sectionName", "keyName", typeof(Int32)];
iniDoc["sectionName", "keyName", typeof(Rectangle)] =
    new Rectangle(0, 0, 200, 300);
//Getting and setting specific type values excepts string
//Primitive Types (included Decimal and DateTime)
//TA_INIDocument.Get{PrimitiveTypeName}(sectionName, keyName, [defaultValue])

bool bValue = 
    iniDoc.GetBoolean("sectionName", "keyName");

bool bValue = 
    iniDoc.GetBoolean("sectionName", "keyName", true);

iniDoc.SetValue("sectionName", "keyName", bValue);

DateTime dtValue = 
    iniDoc.GetDateTime("sectionName", "keyName");

DateTime dtValue = 
    iniDoc.GetDateTime("sectionName", "keyName", DateTime.MaxValue);

iniDoc.SetValue("sectionName", "keyName", dtValue);
//Other types (required that the type has TypeConverterAttribute)
//TA_INIDocument.GetValue<T>(sectionName, keyName, [T:defaultValue])

Rectangle rtValue =
    iniDoc.GetValue<Rectangle>("sectionName", "keyName");

Rectangle rtValue =
    iniDoc.GetValue<Rectangle>("sectionName", "keyName", Rectangle.Empty);

iniDoc.SetValue("sectionName", "keyName", rtValue);

辅助函数

//Helper Properties and Functions
TA_INIDocument iniDoc;
//Getting All Section Names
string[] sectionNames = iniDoc.SectionNames;
//Getting All Key Names of a Section
string[] keyNames = iniDoc.KeyNames("sectionName");
//Getting All Values of a Section
string[] allValues = iniDoc.SectionValues("sectionName");
//Check if section name exits
if (iniDoc.HasSection("sectionName"))
    Application.DoEvents();
//Check if key name exits of specified section
if (iniDoc.HasKey("sectionName", "keyName"))
    Application.DoEvents();

保存所有

//Saving all data
TA_INIDocument iniDoc;
Stream iniStream;

iniDoc.Save(iniStream);
//or
iniDoc.Save(iniStream, Encoding.Unicode);
//or
iniDoc.Save("C:\\sample.ini");
//or
iniDoc.Save("C:\\sample.ini", Encoding.Unicode);
© . All rights reserved.