精通
英语
和
开源
,
擅长
开发
与
培训
,
胸怀四海
第一信赖
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:
每次需要处理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.
我会提出我的图书馆的三个主要使用指南:用户模式,性交模式和轻模式。
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类文件将保留其格式。
结论:用户模式很酷,不是吗?
Actually, this library contains 10 classes. The first two are implementations of StreamReader and StreamWriter:
The second group of classes is used by User-Mode:
An INI file's Elements are the core objects of the IniFiles namespace. Usually they represent single lines of afile, but sometimes more.
The class IniFileElement is a base class for them all. It has standard properties that are used by Reader andWriter:
IniFileSettigs is a static class that contains all format settings used by other parts of the library. Sample settings are:
其实,这个库包含10类。前两个是的StreamReader和StreamWriter的实现:
类的第二组所使用的用户模式:
What can you do with the Hardcore-Mode? What can you gain?
你可以做什么用的硬核模式?你能获得什么?
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文件库!