Upgrade Your INI Files to XML with .NET

Upgrade Your INI Files to XML with .NET

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 (

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 element can contain any number of child or

elements, each of which can contain any number of or elements.

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 element, and then updates that item’s value attribute with the specified new value. The Windows API function WritePrivateProfileString creates new sections and items if you call it with a section or key name that doesn’t already exist.

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:

   [testing]   emp1=Bob Johnson|Accounting|04/03/2001 8:23:14|85   emp2=Susan Fielding|Sales|03/23/2001 15:41:48|92 

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 elements. For example, the following XML listing shows the same data shown in the preceding INI file added as custom attributes.

           Company employees     

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 elements. These methods would be overloaded to accept an element name and value, an XmlElement instance, or an XmlDocumentFragment instance, so you could make the file as complicated as necessary. The Extensibility button on the sample form contains code that shows how to use the extensibility methods.

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
You use the SetIniComments and GetIniComments methods to add and retrieve comments. The GetIniComments method returns a StringCollection containing the text of comments at either the file or section level. The SetIniComments method accepts a StringCollection containing a list of comments you want to add at either the file or section level. While this implementation is very crude, and could be greatly improved?for example, you could extend the class to attach comments directly to individual items?it’s already an improvement over standard INI files, which provide no way to create or remove comments automatically. You can also add XML-formatted comments manually or use the DOM directly to add comments to an XML-formatted INI file.

Where’s My INI File?
For straightforward (unextended) files, you can “get the original INI file back.” In some cases, you will want to read and modify the INI file with a .NET application, but you still need access to the file in its original format usable by pre-.NET Windows applications. An XSLT transform performs the work of turning the file back into a standard INI file. You initiate the transform using the SaveAsIniFile method. However, extensibility comes at a price. If you make custom modifications to the file using the writeCustomIniAttribute method, those changes will not appear in the results of the transform. As there’s little reason to translate the files back to standard INI format, that seems reasonable.

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 Process

At 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 Journalist

©2024 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.