【C#】读取ini配置文件的内容

一、编写ini配置文件

ini文件时初始化文件,通常是系统配置文件所采用的存储格式。ini文件有自己的固定格式,是由若干个“节”(section)组成,每个节由若干个“键”(key)组成,每个key可以赋值相应的“值”(value)。

以下是ini文件的示例,我们将读取name的值。我这里的项目是窗体应用程序。

[section]
name=aline
age=18

二、效果图

三、C# 读取ini文件

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);

        }
    }
}

说明:

ReadIniData()是读取ini文件,四个参数分别是:①section  ini文件里的节(要和ini文件里的一致);②key 要读取的键(如:name、age);③NoText对应API函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的Value时,就用NoText的值来代替;④iniFilePath  ini文件路径

猜你喜欢

转载自blog.csdn.net/qq_25285531/article/details/134782268