[C#] Read the contents of the ini configuration file

1. Write ini configuration file

ini file is an initialization file, usually the storage format used by the system configuration file. ini file has its own fixed format, which is composed of several "sections". Each section is composed of several "keys", and each key can be assigned a corresponding "value".

Below is an example of ini file, we will read the value of name. My project here is a forms application.

[section]
name=aline
age=18

2. Effect drawing

3. C# reads ini file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region API函数声明
        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        #endregion

        #region 读Ini文件

        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        #endregion

        // 读取ini文件 按钮
        private void button1_Click(object sender, EventArgs e)
        {

            //配置文件路径
            string iniFilePath = Directory.GetCurrentDirectory() + "\\app.ini";

            //MessageBox.Show(iniFilePath);
            string Section = "section";
            string Key = "name";
            string NoText = "NoText";

           string res = ReadIniData(Section, Key, NoText, iniFilePath);

           MessageBox.Show(res);

        }
    }
}

illustrate:

ReadIniData() reads the ini file. The four parameters are: ① section The section in the ini file (must be consistent with the ini file); ② key The key to be read (such as name, age); ③ NoText corresponding to the API function def parameter, its value is specified by the user. When the specific Value is not found in the configuration file, the value of NoText is used instead; ④ iniFilePath ini file path

Guess you like

Origin blog.csdn.net/qq_25285531/article/details/134782268