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. devx-admin
Share the Post:
![]() ![]() Tech Layoffs Are Getting Worse Globally
Jordan Williams
September 29, 2023
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 ![]() ![]() Huawei Dazzles with Electric Vehicles and Wireless Earbuds
Johannah Lopez
September 29, 2023
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 ![]() ![]() Digital Banking Needs Cybersecurity
Johannah Lopez
September 29, 2023
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 ![]() ![]() Terry Clune’s Fintech Empire
Grace Phillips
September 29, 2023
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?
DevX Editor
September 29, 2023
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 ![]() ![]() The Future of AI and the Investment Opportunities it Presents
DevX Editor
September 29, 2023
There is no doubt that modern technology has changed the way we live and work forever. Nowadays, there is a wide array of different types ![]() ![]() Tech Layoffs Are Getting Worse Globally
Jordan Williams
September 29, 2023
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 Dazzles with Electric Vehicles and Wireless Earbuds
Johannah Lopez
September 29, 2023
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 ![]() ![]() Digital Banking Needs Cybersecurity
Johannah Lopez
September 29, 2023
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 ![]() ![]() Terry Clune’s Fintech Empire
Grace Phillips
September 29, 2023
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?
DevX Editor
September 29, 2023
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 ![]() ![]() The Future of AI and the Investment Opportunities it Presents
DevX Editor
September 29, 2023
There is no doubt that modern technology has changed the way we live and work forever. Nowadays, there is a wide array of different types of technologies such as AI ![]() ![]() Is Generative AI the Next Internet?
Lila Anderson
September 29, 2023
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 ![]() ![]() The New Surface Laptop Studio 2 Is Nuts
Noah Nguyen
September 29, 2023
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 ![]() ![]() GPU-Accelerated 5G in Japan
Johannah Lopez
September 28, 2023
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 Journalism: Balancing Integrity and Innovation
Grace Phillips
September 28, 2023
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 ![]() ![]() Big Deal Days Extravaganza
Lila Anderson
September 28, 2023
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 Sparks Tech Acquisition Frenzy
Jordan Williams
September 28, 2023
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’s Jet-Propelled Drone Reshapes Power Balance
Jordan Williams
September 28, 2023
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 ![]() ![]() Did the Overshoot Commission Shoot Down Geoengineering?
Johannah Lopez
September 28, 2023
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 ![]() ![]() Revolutionizing Remote Learning for Success
Noah Nguyen
September 28, 2023
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 ![]() ![]() SABERS Batteries Transforming Industries
Grace Phillips
September 28, 2023
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 ![]() ![]() How Much Does It Cost to Build a Website?
DevX Editor
September 28, 2023
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 Startups Attract Billion-Dollar Investments
Lila Anderson
September 28, 2023
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 ![]() ![]() Microsoft Copilot: A Suit of AI Features
Noah Nguyen
September 28, 2023
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 Threatens Relationships
Grace Phillips
September 27, 2023
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 ![]() ![]() Senser is Changing AIOps
Lila Anderson
September 27, 2023
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 ![]() ![]() Check Out The New Bebob Battery Charging Stations
Noah Nguyen
September 27, 2023
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 ![]() ![]() Malaysia’s Dual 5G Network Growth
Jordan Williams
September 27, 2023
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 ![]() ![]() Pentagon’s Bold Race for Advanced Drones
Johannah Lopez
September 27, 2023
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 ![]() ![]() You Need to See the New Microsoft Updates
Johannah Lopez
September 27, 2023
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 |