Is there any class in the .NET framework that can read/write standard .ini files:
[Section]
<keyname>=<value>
...
Delphi has the TIniFile
component and I want to know if there is anything similar for C#?
Is there any class in the .NET framework that can read/write standard .ini files:
[Section]
<keyname>=<value>
...
Delphi has the TIniFile
component and I want to know if there is anything similar for C#?
I found this simple implementation:
http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c
Works well for what I need.
Here is how you use it:
Here is the code:
Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.
Preface
Firstly, read this MSDN blog post on the limitations of INI files. If it suits your needs, read on.
This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET installed, (i.e. Windows 98 - Windows 10). I hereby release it into the public domain - you're free to use it commercially without attribution.
The tiny class
Add a new class called
IniFile.cs
to your project:How to use it
Open the INI file in one of the 3 following ways:
You can write some values like so:
To create a file like this:
To read the values out of the INI file:
Optionally, you can set
[Section]
's:To create a file like this:
You can also check for the existence of a key like so:
You can delete a key like so:
You can also delete a whole section (including all keys) like so:
Please feel free to comment with any improvements!
This article on CodeProject "An INI file handling class using C#" should help.
The author created a C# class "Ini" which exposes two functions from KERNEL32.dll. These functions are:
WritePrivateProfileString
andGetPrivateProfileString
. You will need two namespaces:System.Runtime.InteropServices
andSystem.Text
.Steps to use the Ini class
In your project namespace definition add
Create a INIFile like this
Use
IniWriteValue
to write a new value to a specific key in a section or useIniReadValue
to read a value FROM a key in a specific Section.Note: if you're beginning from scratch, you could read this MSDN article: How to: Add Application Configuration Files to C# Projects. It's a better way for configuring your application.
If you want just a simple reader without sections and any other dlls here is simple solution:
Usage sample:
Config file content meanwhile (as you see supports # symbol for line comment):