he INI (application INItialization) file format became popular because it provided a convenient way to store values that might change (such as file locations, user preferences, etc.) in a standard format accessible to but outside of compiled application code. INI files are text-based, meaning you can read and change the values easily; logically arranged, meaningit is easy even for non-technical personnel to understand the contents; and the functions for reading and modifying the files were built into Windows.
In a recent featured discussion on DevX (see Use COM Interop to Read and Write to INI Files with .NET) I explained how to read and write INI files with .NET using DllImport to access the Windows API functions from within a C# or VB.NET class. Although the DllImport method lets you use existing INI files from .NET, it doesn’t do anything to solve the problems inherent in the INI file format itself?and INI files have a number of deficiencies. For example, total file size is limited to 64Kb total, individual values cannot exceed 256 characters, and the Windows API provides no programmatic way to read and write comments. Translating the files to XML solves these problems.
The Ubiquitous INI File
An INI file has three types of information: sections, keys, and values. A section is a string enclosed in square brackets. The keys and values are paired. A key does not have to have a value, but when present, an equals (=) sign separates the key from the value. The keys and values together create an item. The items are always “children” of a section header. Each section can have any number of child items. For example, here’s a simple INI file structure:
[Section 1] key=value [Section 2] key=value key=value
INI files first appeared in Windows 3.x, and were originally intended to hold global Windows settings for various applications. Therefore, the section items of the INI file format were initially called application?a name that persists in the Win32 API function calls to this day, even though the later documentation uses the section/key/value terminology. Windows provides special APIs to read and write the win.ini file in the $Windows folder, as well as functionally identical “private” versions that read and write values from named INI files specific to one application. Windows provides a number of functions in kernel32.dll to read and write INI files?all of which are marked as obsolete ( http://msdn.microsoft.com/library/default.asp?url=/library/en-us/win32/obsol_044z.asp).
Microsoft began calling the API functions obsolete seven years ago with the release of Windows 95, when it began touting the Registry as the perfect place to store application-level settings. The current MDSN documentation states that the functions are supported only for backward compatibility with Win16. Nevertheless, INI files have remained popular among developers, partly because Microsoft never made the Registry easy to use programmatically, and partly for many of the same reasons that XML became popular: INI files are easy to understand, easy to modify, either manually or programmatically, and you can simply copy them from one machine to another. Interestingly, despite Microsoft’s insistence that INI files are obsolete, they’re ubiquitous even in Microsoft software (search your local Documents and Settings folderaccountNameLocal SettingsApplication Data folder for examples).
Why Not Use .NET Configuration Files?
.NET applications are supposed to use the AppSettings section of configuration files to store key/value pair information. Unfortunately, the INI file format doesn’t translate well to a simple list of key-value pairs, because you lose a “level” of information. Items in INI files exist as children of named sections; therefore many INI files repeat key names for each section. Any line in an INI file that starts with a semicolon is a comment. For example, the sample code uses this INI file:
; Company employees [Employee1] name=Bob Johnson department=Accounting [Employee2] name=Susan Fielding department=Sales
If you were to remove the section names and try to place this information into a configuration file as key/value pairs, you would have duplicate key names. In other words, the default AppSettings data provides no way to group the items into something equivalent to INI sections. You could write a custom configuration handler?and I considered doing that for this article, but finally decided to do that in a later article, as simply translating the INI file to XML is both simpler to understand and easily extensible (more on extensibility later).
The IniFileReader project sample code that accompanies this article reads standard INI files or XML-formatted INI files (see Table 1 for a complete list of methods and properties). The IniFileReader class constructor requires a file name. The class first tries to open the specified file as an XML file, using the XmlDocument.Load method. If that fails, the class assumes the file is in the INI format. It then creates a very simple default XML string and loads that, using the XmlDocument.LoadXml method, after which it opens the file in text mode and parses the lines of the file adding elements for the sections, items, and comments in the order they appear (see Listing 1). As an example, the sample INI file shown earlier looks like this after the IniFileReader finishes loading it.
Company employees
Getting the INI file contents into this simple XML structure makes it easy to mimic and extend the actions that you can perform with a standard INI file?and makes them easier to remember. The root
One question you may have: Why doesn’t the project use the standard API functions through DllImport as discussed in Use COM Interop to Read and Write to INI Files with .NET? The answer is that the standard API functions provide no way to read comments, so you can’t get a complete translation using the API functions alone. Instead, for this particular purpose, it’s better to parse the file line by line.
Retrieving Values
To retrieve the value of an item, you use the GetIniValue method, which accepts sectionName and keyName parameters. The method creates an XPath query that searches for the section with a name attribute matching the supplied section name, and then searches within that section for an item with a key attribute matching the supplied key name. If the XPath query matches an item, the function returns the text value of the value attribute of that item; otherwise it returns null.
public String GetIniValue(String sectionName, String keyName) { XmlNode N = null; if ((sectionName != null) && (sectionName != "") && (keyName != null) && (keyName != "")) { N = GetItem(sectionName, keyName); if (N != null) { return(N.Attributes.GetNamedItem ("value").Value); } } return null; }
There is one major difference between XML-formatted files and INI files?XML files are case sensitive, while standard INI files aren’t. The INIFileReader class deals with this by treating all data as case-insensitive by default. See the sidebar “Dealing With XML’s Case Sensitivity” for a more detailed explanation.
Updating individual values is similar to retrieving them. You provide a section name, a key name, and the new value. The class uses the GetItem method to locate the appropriate
Although it’s not good object-oriented design, for consistency the IniFileReader class acts identically, meaning that you can create a new section simply by passing a nonexistent section name. To update a section name, key name, or value for existing sections or items, select the section and item you want to update, enter the new values in the appropriate fields, and then click the Update button to apply the changes. To create a new section or key on the sample form, first click the New Section or New Key button to clear the current selections, and then enter the new section or key name and click the Update button to apply your changes.
To delete a section using the API, you pass the section name and a null key value to the WritePrivateProfileString function?and you do the same with the IniFileReader class, except that you use the SetIniValue method. For example, the following code would delete the section named section1.
SetIniValue("section1", null, null);
Similarly, to delete an item within a section, you pass the section name, the key name, and a null value for the value argument. The following code would delete the item with the key key1 in the section named section1.
SetIniValue("section1", "key1", null);
On the sample form (see Figure 1), you can delete a section or value by selecting the appropriate item in either the section or item list, and then pressing the Delete key.
The three types of information in a standard INI file often did not suffice to store the information needed by the application. I’ve seen (and built) applications that rely on custom string formats to perform tasks beyond the INI file format’s native capabilities. For example, it’s not uncommon to see INI files that contain strings that use separators to “squash” more values into an INI file:
Not only are such files difficult to read and edit?and maintain?but they also require custom code to retrieve the item values and assign them to variables within the program. The data in such files is unusable by other programs without recreating the code to retrieve the data. In contrast, you can add new items to an XML-formatted INI file with few problems. At the most simplistic level, you can use the GetCustomIniAttribute and SetCustomIniAttribute methods to read, write, and delete custom strings, stored as attributes within the
It’s much easier to discover the meaning of the data in the XML version. At a more complex level, although I haven’t implemented it in the sample code, you could add GetCustomIniElement and SetCustomIniElement methods to add custom child elements and values to the Beyond the built-in extensibility methods, you can, of course, subclass the IniFileReader and override or add methods to do anything you like. Dealing with Comments Where’s My INI File? Having a separate file for storing application initialization information is a good idea. The .NET framework contains built-in methods for handling configuration data, but?as delivered?they aren’t suitable for complex information structures. As you migrate existing applications into .NET, the INIFileReader class described in this article lets you use and even extend your existing INI files. Nonetheless, .NET configuration files have some advantages even over these custom external XML-formatted initialization files. In a future article, I’ll show you how to achieve the same level of functionality using a custom configuration handler, which will let you place configuration data directly into your machine.config or application configuration file. About Our Editorial ProcessAt DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere. See our full editorial policy. About Our JournalistCharlie Frank Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience. View Author Anticipating Bitcoin’s halving: impacts and strategies Rashan Dixon April 19, 2024 Nothing startup integrates ChatGPT into devices Rashan Dixon April 19, 2024 Google Maps enhances search for EV charging stations Cameron Wiggins April 19, 2024 Upcoming social security payments scheduled by birth dates Rashan Dixon April 19, 2024 Retirees to receive double Social Security payments soon Noah Nguyen April 19, 2024 Proposed Act Aims to Adjust Social Security for Seniors Rashan Dixon April 19, 2024 Anticipating Bitcoin’s halving: impacts and strategies Rashan Dixon April 19, 2024 5:39 PM Nothing startup integrates ChatGPT into devices Rashan Dixon April 19, 2024 5:06 PM Google Maps enhances search for EV charging stations Cameron Wiggins April 19, 2024 1:28 PM Upcoming social security payments scheduled by birth dates Rashan Dixon April 19, 2024 1:07 PM Retirees to receive double Social Security payments soon Noah Nguyen April 19, 2024 11:59 AM Proposed Act Aims to Adjust Social Security for Seniors Rashan Dixon April 19, 2024 8:33 AM USD/JPY stability holds amidst market ambiguities Cameron Wiggins April 19, 2024 8:27 AM Silver prices surge amid increasing demand Rashan Dixon April 19, 2024 7:52 AM Is Online Bookkeeping the Ideal Side Gig for Remote Workers? Kyle Lewis April 18, 2024 2:49 PM Global stock stability amid rising US interest rates Rashan Dixon April 18, 2024 1:44 PM Rivos Inc. raises $250 million pre-launch for AI chips Noah Nguyen April 18, 2024 1:19 PM Goldman Sachs advises caution in predicting Bitcoin prices Cameron Wiggins April 18, 2024 1:14 PM Predicted rise in social security benefits amid inflation Noah Nguyen April 18, 2024 1:09 PM Gold prices dip amid assertive fiscal comments Johannah Lopez April 18, 2024 11:46 AM Vorlon raises $15.7M to strengthen API security Noah Nguyen April 18, 2024 11:28 AM Last April social security disbursement approaching Johannah Lopez April 18, 2024 11:16 AM Rippling to pursue substantial funding round Johannah Lopez April 18, 2024 8:33 AM Simpson’s lawyer battles to protect estate from Goldmans Noah Nguyen April 18, 2024 8:31 AM April’s Social Security retirement payments underway Cameron Wiggins April 17, 2024 5:54 PM Rivian develops software to rank EV chargers Rashan Dixon April 17, 2024 5:50 PM Simpson’s will leaves Goldman family uncompensated April Isaacs April 17, 2024 5:26 PM Framework grapples with software sustainability issues Noah Nguyen April 17, 2024 3:44 PM Surprising economic growth attributed to China’s robust exports and domestic demand Rashan Dixon April 17, 2024 3:04 PM COBOL at 65: still a powerhouse in the tech industry Cameron Wiggins April 17, 2024 1:59 PM California’s minimum wage hike worries restaurateurs Noah Nguyen April 17, 2024 1:05 PM |