锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 开源技术 / C#开源英语 / C#INI文件处理类
服务方向
人工智能数据处理
人工智能培训
kaldi数据准备
小语种语音识别
语音识别标注
语音识别系统
语音识别转文字
kaldi开发技术服务
软件开发
运动控制卡上位机
机械加工软件
软件开发培训
Java 安卓移动开发
VC++
C#软件
汇编和破解
驱动开发
联系方式
固话:0371-63888850
手机:138-0381-0136
Q Q:396806883
微信:ryysoft

简介


It is strange to write a parser of INI files each time it is needed. Why not use an existing one, especially if it is good? I give you a class library that has the following features:

  • Parses INI files using given format directions.
  • Edits them easily using one single class.
  • Automatically finds out a formatting convention.
  • Adds commentaries to the sections and values just by setting a property Comment.
  • Writes a file to the disc, preserving its original format.
  • Enjoys richly documented code.

每次需要处理INI文件时,再写INI解析器,这有点奇怪。为什么不使用现有的,尤其是如果它是好的?我给你一个类库,它具有以下特点:

  • 使用给定的格式化方向解析INI文件。
  • 以一个单独的类编辑,易用。
  • 自动发现一个格式化约定。
  • 只需通过设置注释属性添加节和值的注释。
  • 将文件写入到磁盘上,保留了其原有的格式。
  • 享受注释丰富的代码。

背景

INI [=initialization] files are used to store settings that define the start-up state of some programs. Alternatively, they can just contain configuration data. Currently they can be found in special folders (desktop.ini) like "My Documents." A lot of them exist in the Windows root folder, e.g. C:\Windows\win.ini. In this article, I will use the following terminology:

INI[=初始化]文件用于存储设置,定义某些程序的启动状态。或者,他们可以只包含配置数据。目前,他们可以在特殊文件夹(有desktop.ini),如找到“我的文档”。他们中的很多存在于Windows根目录下,如C:\ WINDOWS\ win.ini中。在这篇文章中,我将使用以下术语:

[Abcd]  <- "Section"  Number=188  <- "Key" (vel "Value name") and "Value"

使用代码

I will present three main usage guides of my library: User-Mode, Hardcore-Mode and Light-Mode.

我会提出我的图书馆的三个主要使用指南:用户模式,性交模式和轻模式。

User-Mode

The IniFile namespace contains one class: IniFile. It represents an object model of an INI file, which stores a whole structure in memory. Usage of IniFile is extremely simple.

ini文件命名空间包含一个类:INI文件。它代表INI文件,其中存储的整体结构在存储器中的对象模型。 INIFILE的使用非常简单。

IniFile file = new IniFile();  
// Adds a new section with one value    
file["LastUser"]["Name"] = "Gajatko";  
// Save to disc    file.Save("test.txt");

This will give the following output:

这会给下面的输出:

[LastUser]  Name=Gajatko

The indexer of IniFile returns an object that also has an indexer. However, it also has many other features. For example, it has a Comment property:

INI文件中的索引会返回一个对象,也有一个索引。但是,它也有许多其他功能。例如,它有一个Comment属性:

file["LastUser"].Comment =  @"This section contains information about user  which logged in at previous program run";  
file["LastUser"].SetComment("Name", "Name of user");

Result:

结果:

;This section contains information about user  
;which has logged in at previous program run  
[LastUser]  
;Name of user  Name=Gajatko

We can freely manipulate values and sections:

我们可以自由地操纵值和部分:

// Rename sections and keys    
file["LastUser"].Name = "RecentUser";  
file["RecentUser"].RenameKey("Name", "Login");  
// Get names of all section:   
string[] sections = file.GetSectionNames();  
// Set existing values:    
file["RecentUser"]["Login"] = "Chuck";  
// Override existing comment:    
file["RecentUser"].Comment = "New Comment";

Result:

结果:

;New Comment  [RecentUser]  ;Name of user  Login=Chuck

Also, inline comments are supported:

此外,行内注释的支持:

file["RecentUser"].InlineComment = "An inline thing";

Result:

结果:

[RecentUser]   ;An inline thing

We can save all changes to a file and read from it, as well:

我们可以保存所有修改的文件,并从中读取,还有:

file.Save("test.txt");  file = IniFile.FromFile("test.txt");

More methods and properties will appear in the auto-completion service in Visual Studio. They are all commented using Summary blocks. Files edited with the IniFile class will preserve their formatting.

Concluding: the User-Mode is cool, isn't it?

更多的方法和属性将出现在Visual Studio中的自动完成的服务。他们使用的是总结阻止所有评论。编辑与INIFILE类文件将保留其格式。

结论:用户模式很酷,不是吗?

Hardcore-Mode

Classes

Actually, this library contains 10 classes. The first two are implementations of StreamReader and StreamWriter:

  • IniFileReader - Reads and parses a text file.
  • IniFileWriter - Writes INI file elements to a disc.

The second group of classes is used by User-Mode:

  • IniFile - Contains the whole INI file in memory and enables easy access to it.
  • IniFileSection - Represents a section and its values.

An INI file's Elements are the core objects of the IniFiles namespace. Usually they represent single lines of afile, but sometimes more.

  • IniFileSectionStart - Represents a beginning line of a section, like "[LastUser]".
  • IniFileValue - Represents a single line with a value, like "Name=Gajatko".
  • IniFileBlankLine - Represents one or more blank lines. The actual number of them is specified in theAmount property.
  • IniFileComment - Represents one or more commentary lines.

The class IniFileElement is a base class for them all. It has standard properties that are used by Reader andWriter:

  • Line - An actual representation of the object in the INI file. The name is a little confusing because sometimes the Line contains more than one line.
  • Content - Similar to Line, but without indentation.
  • Indentation - A string of all white spaces (tabs, spaces) preceding a meaningful content.
  • Formatting - A formatting string specific to a particular type of INI file element.

IniFileSettigs is a static class that contains all format settings used by other parts of the library. Sample settings are:

  • PreserveFormatting - Default true. If set to false, the Format() method will be called for all INI fileelements while writing a file. The demo shows how it works.
  • CommentChars - Array of strings that begin a comment line, by default { ";", "#" }. When adding new comments, the first string in the array is used.
  • GroupElements - As said before, when the parser runs into a multiline commentary or blank lines, it will group them into one object. Setting this property to false will prevent this practice.
  • QuoteChar - A nullable char. Default value is null, but can be set to e.g. " (double qoutation mark). Then all values will be surrounded by quotes. However, either calling the Format() method or settingPreserveFormatting to false will be necessary.
  • DefaultValueFormatting - A spectacular property that defines a default appearance of values. The default is "?=$ ;" which causes values look like this: "Key=Value ;comment".
  • ... and much more (totally 16 properties).

其实,这个库包含10类。前两个是的StreamReader和StreamWriter的实现:

  • ini文件阅读器 - 读取和分析的文本文件。
  • INI的FileWriter - 写入INI文件内容到光盘。

类的第二组所使用的用户模式:

  • INIFILE - 包含内存中的整个INI文件,并能够方便地访问它。
  • IniFileSection - 代表一个部分,它的价值。
  • ini文件中的元素是IniFiles命名空间的核心对象。通常他们所代表的单线条å文件,但有时更多。
  • IniFileSectionStart - 代表一个开端线的截面,如“[LastUser]”。
  • IniFileValue - 表示与值的单行线,如“名称= Gajatko”。
  • IniFileBlankLine - 代表一个或多个空行。被指定在theAmount属性他们的实际数目。
  • IniFileComment - 代表一个或多个注释行。
  • 类IniFileElement是他们所有的基类。它具有所使用的读卡器andWriter标准属性:
  • 线 - 在INI文件对象的实际表现。这个名字是有点混乱,因为有时行包含多条线路。
  • 内容 - 类似于线,但没有缩进。
  • 压痕 - 一个字符串的所有空白(制表符,空格)一个有意义的内容前面的。
  • 格式 - 专用于特定类型的INI文件元素的格式化字符串。
  • IniFileSettigs是包含库所使用的其他部分全格式设置一个静态类。示例设置如下:
  • PreserveFor​​matting - 默认为true。如果设置为false,格式()方法将被用于所有INI fileelements同时写入文件。该演示展示了它是如何工作的。
  • CommentChars - 开头注释行,默认字符串数组{“;”,“#”}。当添加新的评论,数组中的第一个字符串使用。
  • GroupElements - 正如前面所说,当解析器运行到一个多行注释或空行,这将把他们到一个对象。该属性设置为false将阻止这种做法。
  • QuoteChar - 可空字符。默认值是空的,但可以设定为例如“(双qoutation标记)。然后,所有值将被用引号包围着,然而,无论是调用格式()方法或settingPreserveFor​​matting为false将是必要的。
  • DefaultValueFormatting - 一个壮观的属性定义值的默认外观。默认为“= $;?”这将导致价值观是这样的:“键=值;评论”。
  • ......等等(共16属性)。

用法

What can you do with the Hardcore-Mode? What can you gain?

  • Be faster.
  • Read only the values that you need.
  • Feel like a Hardcore Boss.

你可以做什么用的硬核模式?你能获得什么?

  • 更快。
  • 只读您需要的值。
  • 感觉像一个铁杆老板。

Sample scenario #1: You want to extract a single section from an INI file instead of loading a whole file into a dummy ConfigFile class from User-Mode. We will use IniFileReader here. Our goal is to extract the "Mail" section from win.ini to the separate file without loading all other sections.

示例场景#1:要提取从INI文件,而不是加载整个文件到从用户模式的虚拟配置文件级的一个节。我们将使用的FileReader这里。我们的目标是提取win.ini中的单独的文件中的“邮件”部分,而无需装载所有其它部分。

IniFileReader reader = new IniFileReader("win.ini");  
// Find the section without parsing lines before it.    
reader.GotoSection("Mail");  
// Get section's content    
List<IniFileElement> sectionElements = reader.ReadSection();  
// Do not load the rest. Close the stream.    
reader.Close();    
// Write the section.    
IniFileWriter writer = new IniFileWriter("mail.ini");  
writer.WriteElements(sectionElements);  
writer.Close();

A very good idea is to create an IniFile object from the extracted collection:

一个很好的想法是从提取的集合创建一个INI文件对象:

IniFile file = IniFile.FromElements(sectionElements)

Such an IniFile would contain one section: the extracted "Mail." This enables a whole set of methods specific to User-Mode, including lazy commenting entries and easy modifying values.

Sample scenario #2: You want to get just ONE value from a file. Let's say that this value is "OLEMessaging" from the "Mail" section in win.ini.

这样的ini文件应包含一个部分:提取“邮件。”这使得一整套针对用户模式的方法,包括懒惰注释的条目,易于修改的值。

示例场景2:你想从一个文件中只是一个值。比方说,这个值是“OLEMessaging”从win.ini中的“邮件”部分。

IniFileReader reader = new IniFileReader("win.ini");  
reader.GotoSection("Mail");  
// I do not remember how olemessaging's characters exactly look,    
// so I set case-sensitivity to false (default true).    
IniFileSettings.CaseSensitive = false;  
IniFileValue val = reader.GotoValue("olemessaging");  
reader.Close();  string oleMsg = val.Value;  
// ... (do something with oleMsg).

...and so on.

...等等。

光模式

IniFileReader and IniFileWriter are fast. IniFile is a bit slower, although the main slowdown appears while loading a file, not performing operations. For yet higher performance, I have written an additional class in a separate namespace: IniFiles.Light.IniFileLight. It enables parsing and writing of INI files. However, it totally ignores formatting and blank lines. Everything will be written using the following pattern:

在的FileReader和FileWriter的快。 INFILE是有点慢,但在加载一个文件,而不是执行操作的主要经济放缓出现。对于尚未更高的性能,我在不同的命名空间编写了一个额外的类:IniFiles.Light.IniFileLight。它能够解析INI文件和写作。但是,它忽略了格式和空行。一切都将通过以下方式写:

[Section]  Key=Value

It enables commenting values, but only single-line. The usage is similar to the User-Mode:

它使评论值,但只有单行。用法是类似于用户模式:

// Create a new file  Gajatko.IniFiles.Light.IniFileLight light =       
new Gajatko.IniFiles.Light.IniFileLight();  
// Set some data  
light.Sections.Add("Data", new Dictionary<string, string>());  
light.Sections["Data"].Add("Name", "Mickey");  
light.Sections["Data"].Add("Surname", "Mouse");  
// Add comments  
light.Comments.Add("Data.Surname", "This is a surname");  
light.Comments.Add("Data", "This is a section");  
// Set a footer  
light.Comments.Add("", "Footer");  
// Save to a file  
light.Save("light.txt");

Output:

输出:

;This is a section  [Data]  Name=Mickey  ;This is a surname  Surname=Mouse  ;Footer

You know the limitations of such a solution, so it's up to you which variant you use. I put the IniFileLight in a separate namespace because if somebody wants to use it, he probably wouldn't like to have all my 10 classes in the auto-completion list.

你知道这种解决方案的局限性,所以它是由你哪个变体使用。我把ini文件光在不同的命名空间,因为如果有人想使用它,他可能不会喜欢有我所有的10类中的自动完成列表。

格式保留

Nobody forces you to use this IniFiles's skill; it can run in the background and not bother you. However, if you want to make your INI files look as originally or you are parsing ones which look as originally, I tell you that my code will not loose any content of a file. How much does the parser preserve the format? Here are some samples.

没有人强迫你使用这个IniFiles技能;它可以在后台运行,并不会打扰你。但是,如果你想使你的INI文件看起来像原来还是你解析那些它最初的样子,我告诉你,我的代码将不会丢失文件的任何内容。多少解析器保留格式?这里有一些样品。

[Section1]      Key1=  Value1

Look how Key1 looks. After the equality sign there are two spaces. If you add a new value to Section1, it will preserve this appearance and indentation:

看看键1的外观。等号后有两个空格。如果将一个新值添加到第1,它会保持这种外观和缩进:

[Section1]      Key1=  Value1      NewKey=  NewValue

Section1 is a little indented. If you add a new section, it will be a little indented too.

第1节是一个小凹陷。如果添加了一个新的部分,这将是一个有点缩进了。

[Section1]      Key1=  Value1      NewKey=  NewValue    [NewSection]

Section1 is a little indented. If you add a new section, it will be a little indented too.

如果你现在是一个值添加到第2节,它的外观一样的一节中的最后一个值:

[Section1]      Key1=  Value1      NewKey=  NewValue    [NewSection]      FreshKey=  FreshValue

Let's consider a section with such an appearance:

让我们考虑一个截面,这样的外观:

[ Section1 ]  Key1=Value1

Then a new added one will follow the template:

然后,一个新增加了一个将遵循模板:

[ Section1 ]  Key1=Value1  [ New Section ]

Also, indentation of comments and blank lines are saved. There are situations when a conflict appears. Here is one of them: If quotes are on (IniFileSettings.QuoteChars = "\""), then we can imagine the following piece:

另外,注释和空行缩进被保存。存在这样的情况出现冲突的时候。下面就是其中之一:如果报价上(IniFileSettings.QuoteChars=“\”“),那么我们可以想像下面一段:

[Section1]  Key1="Value1" some text

It is obvious that the value of Key1 is 'Value1', not 'Value1" some text' or something like that. The parser knows that, so it interprets ' some text' as a TextOnTheRight. This also will be preserved. However, this behaviour can be changed through the IniFileSettings.AllowTextOnTheRight property.

很明显,键1的值是“值1”,而不是“值1”一些文本“或类似的东西。分析器都知道这一点,所以它解释”一些文本“作为TextOnTheRight,这也将被保留。但是,这行为可以通过IniFileSettings.AllowTextOnTheRight属性来改变。

Format preserving can be turned off by switching IniFileSettings.PreserveFormatting to false. However, you may want to save the indentation of elements. Then call the IniFile.Format(false) method to format everything excluding leading spaces, or IniFile[sectionName].Format(false) to format the specified section.

格式保存可以通过切换IniFileSettings.PreserveFormatting到假被关闭。但是,您可能希望保存元素的压痕。然后调用IniFile.Format(假)方法来格式化一切不含前导空格,或INIFILE[sectionName].Format(false)来指定的部分进行格式化。

Download the demo to learn more.

下载演示,了解更多信息。

总结

INI files are not used as often as in the old bad DOS times. Now XML is the king. However, they can still be found in various places and sometimes we have to go back to them. My library is the same for INI files as ASP is for HTML controls, where simple tags on the client side have a rich object model on the server. Being very advanced in its core gives it simple and fast access to all INI file features.

INI文件不只被用作老旧的DOS环境。现在,XML为王。但是,它们仍然可以在不同的地方发现,有时候我们要回头用他们。此库对INI文件的作用,是ASP对HTML控件作用一样,ASP在客户端上提供简单标记,但在服务器上有一个丰富的对象模型支持。作为非常先进的核心,使它简单而快速地访问所有INI文件。

Enjoy the IniFiles library!

享受INI文件库!

历史

  • 21 August, 2007 -- Original version posted
  • 2 July, 2008 -- Download updated
  • 2007年8月21日 - 原始版本发布
  • 2008年7月 - 下载更新
友情链接
版权所有 Copyright(c)2004-2021 锐英源软件
公司注册号:410105000449586 豫ICP备08007559号 最佳分辨率 1024*768
地址:郑州大学北校区院(文化路97号院)内