SoFunction
Updated on 2025-03-06

C# Read and Write Ini Configuration File Example

What others write is calling non-hosted. I have used it, but I feel the compatibility is a bit bad. Sometimes there will be encoding errors, after all, one is the previous system and the other is the current system. Let’s write a pure C# ini format configuration file to read, which is actually reading and writing text files. But what we need to do is not just for the convenience of access and operation, but also for future use.


Everyone knows that each configuration item in the ini format configuration file is actually line by line of text. Key and value are separated by equal signs.
Like this:
grade=5 。
Each configuration item is grouped and the same type is put together. It is called section. It is distinguished by brackets ([]).
Like this:
[contact]
qq=410910748
website=
[score]
math=85
Chinese=90
geographic=60
The keys of each configuration item cannot be repeated within the section.

Here, we have not used it very much for the purpose of removing the concept of section for convenience. In this way, each configuration item can be understood into a dictionary structure, which facilitates our access and other operations. As for why you must use dictionary, because during the test, I found that it will not disrupt the storage order of elements during the access process. It's just like that. We must do it by taking the value according to the key. Also, we need to note that sometimes we need to write comments in the configuration file. It is a line that starts with a semicolon (;). We can initialize a special key+serial number form for this problem in the program, and make the same judgment when writing it.

The whole process is:
When the program starts, iterates through all lines. If it starts with a semicolon (;), this line is stored as a configuration explanation. If it is not, this line is interpreted and placed in the dictionary collection. Getting the value according to the key when accessing is that simple. Pay attention to the processing of comment lines. Also, change the configuration and save the order of the lines that are saved back must be kept as it is.

OK, start work:

Copy the codeThe code is as follows:

public class Config
{
    public Dictionary<string, string> configData;
    string fullFileName;
    public Config(string _fileName)
    {
        configData = new Dictionary<string,string>();
        fullFileName = + @"\" + _fileName;

        bool hasCfgFile =( + @"\" + _fileName);
        if (hasCfgFile == false)
        {
            StreamWriter writer = new StreamWriter(( + @"\" + _fileName), );
            ();
        }
        StreamReader reader = new StreamReader( + @"\" + _fileName, );
        string line;

        int indx = 0;
        while ((line = ()) != null)
        {
            if ((";") || (line))
                (";" + indx++, line);
            else
            {
                string[] key_value = ('=');
                if (key_value.Length >= 2)
                    (key_value[0], key_value[1]);
                else
                    (";" + indx++, line);
            }
        }
        ();
    }

    public string get(string key)
    {
        if ( <= 0)
            return null;
        else if((key))
            return configData[key].ToString();
        else
            return null;
    }

    public void set(string key, string value)
    {
        if ((key))
            configData[key] = value;
        else
            (key, value);
    }

    public void save()
    {
        StreamWriter writer = new StreamWriter(fullFileName,false,);
        IDictionaryEnumerator enu = ();
        while (())
        {
            if (().StartsWith(";"))
                ();
            else
                ( + "=" + );
        }
        ();
    }
}