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 ( 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 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.



Share the Post:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

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