当前位置: 首页 > article >正文

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


http://www.kler.cn/a/157717.html

相关文章:

  • 【Android】HttpURLConnection、OkHttp
  • Nat easy IP ACL
  • 【微软技术栈】与其他.NET语言的互操作性 (C++/CLI)
  • DCDC电源的选择
  • 04、pytest运行多个测试用例
  • 配置Docker OpenWrt与宿主机网络互通且作为宿主机网关
  • CSS实现一些小功能
  • Vue3使用vue-baidu-map-3x百度地图
  • 使用axios下载后端接口返回的文件流格式文件
  • C++ ini配置文件的简单读取使用
  • 【腾讯云云上实验室】个人对腾讯云向量数据库的体验心得
  • 第一节JavaScript 简介与使用
  • springboot-技术栈汇总
  • 3.5毫米音频连接器接线方式
  • Linux scatterlist 详解
  • 【Filament】Filament环境搭建
  • @Scheduled,Quartz,XXL-JOB三种定时任务总结
  • java使用xstream框架生成xml文件
  • MySQL导出ER图为图片或PDF
  • uniapp 云打包 生成安卓证书文件