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

一种简单的架构, 用于将任意格式的平面文件读入 ADO 数据集

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.88/5 (9投票s)

2003年4月26日

2分钟阅读

viewsIcon

63944

downloadIcon

1410

本文提供了一个简单的架构,使用 StreamReader 和 DataSets 结合起来,将任意格式的平面文件中的数据读入 DataSets,以 ini 文件为例

引言

有 Ole 提供程序可以将格式化的平面文件读入 DataSet,但是否想过从并非仅仅是逗号分隔或制表符分隔(非列式)而是某种原生格式的文件中导入数据?

我能想到的最简单的例子之一是 ini 文件。虽然足够简单,但没有列式或分隔数据。那么我们如何使用 C# 将此类文件导入数据库呢?

由于存在 2 个不同的数据部分(节和键/值对),阅读器类使用 System.IO.StreamReader 从指定的 ini 文件中读取行,并在遇到节或键/值对时引发事件。一个数据类,IniFileData 类,有一个 System.Data.DataSet 成员,保存了来自 ini 文件的所有节、键和值。此类订阅来自 IniFileReader 的事件(SectionRead KeyValueRead),创建相应的行并将它们添加到 DataTable 中。

一旦数据被读入 DataSet,就由用户的兴趣来处理它了。我给出了一个小的例子,通过在 IniFileData 类上编写 GetValue() 方法,通过给出节和键名来检索值。

使用代码

创建一个 IniFileData 类的实例并给出一个 ini 文件名。该类读取文件并准备 DataSet

以下代码显示了 IniFileReader 中委托和事件的声明。

// delegate to receive a SectionRead event
public delegate void SectionHandler(string sectionName);
// event raised when a section is read
public event SectionHandler SectionRead;
// delegate to receive a KeyValueRead event
public delegate void KeyValueHandler(string section, 
string key, string sValue); // event raised when a key, value pair is read public event KeyValueHandler KeyValueRead;

StreamReader 读取平面文件时,会触发这些事件。触发这些事件的最合适的方法是当 DataSet 中的任何表中有一行数据可用时。在这里,您可以看到当读取一个节或读取一个键/值对时,会抛出这些事件。

    class IniFileReader
    {    .......
        public void ReadIniFile(string filename) 
        {
            StreamReader sr = new StreamReader(filename);
            ........
            while (not end of file)
            {
                if (oneLine.StartsWith("[") && oneLine.EndsWith("]")) 
                    SectionRead(currentSection); 
// raise the section read event } else { ..... // raise an event if a key/value pair is read KeyValueRead(currentSection, keyvalue[0], keyvalue[1]); } } } }

准备保存 DataSet 的类,在本例中是 IniFileData 类,订阅这些事件并准备行并将它们插入到相应的表中。相关的代码在下面指出。

    class IniFileData
    {
        .....
        public void ReadIniFile(string PathName)
        {
            ......
            IniFileReader ir = new IniFileReader(); 
// create instance of iniFileReader
// subscribe to the event handlers ir.SectionRead += new IniFileReader.SectionHandler(
this.OnSectionRead); ir.KeyValueRead += new IniFileReader.KeyValueHandler(
this.OnKeyValueRead); ...... } private void OnSectionRead(string Section) { // create the sections here ....... } private void OnKeyValueRead(string Section, string Key,
string sValue) { // insert the key value pairs here ....... } }

关注点

IniFileData.GetValue() 方法中,我找不到一种方法,在检索值时在一个查询中连接不同的表。如果我找到了一个,我会在这里发布。

© . All rights reserved.