【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文件路径

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下页、再停留

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值