C# ini 文件读取方法

今天在做的系统中,需要读取配置文件,除了C#读取XML的配置文件的方法外,还可以使用

Windows API读取ini配置文件,今天学到了,写在这里供大家分享,希望大家多多拍砖

using System.Runtime.InteropServices;
using System.Text;

namespace CMP_WX
{
    /**/
    ///  <summary>
    ///  读写ini文件的类
    ///  调用kernel32.dll中的两个API:WritePrivateProfileString,GetPrivateProfileString
    ///  来实现对ini  文件的读写。
    ///  INI文件是文本文件,
    ///  由若干节(section)组成,
    ///  在每个带括号的标题下面,
    ///  是若干个关键词(key)及其对应的值(value)
    ///  例如:
    ///  [Section]
    ///  Key=value
    ///  </summary>
    public class Read_INT
    {
        /**/
        ///  <summary>
        ///  ini文件名称(带路径)
        ///  </summary>
        public string filePath;

        /**/
        ///  声明读写INI文件的API函数
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        /**/
        ///  <summary>
        ///  类的构造函数
        ///  </summary>
        ///  <param  name="INIPath">INI文件名</param> 
        public Read_INT(string INIPath)
        {
            filePath = INIPath;
        }
        /**/
        ///  <summary>
        ///  写INI文件
        ///  </summary>
        ///  <param  name="Section">Section</param>
        ///  <param  name="Key">Key</param>
        ///  <param  name="value">value</param>
        public void WriteInivalue(string Section, string Key, string value)
        {
            WritePrivateProfileString(Section, Key, value, this.filePath);
        }
        /**/
        ///  <summary>
        ///  读取INI文件指定部分
        ///  </summary>
        ///  <param  name="Section">Section</param>
        ///  <param  name="Key">Key</param>
        ///  <returns>String</returns> 
        public string ReadInivalue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(1024);
            int i = GetPrivateProfileString(Section, Key, "读取错误", temp, 1024, this.filePath);
            return temp.ToString();
        }
    }
}

再加一点调用的方法:

//读取ini节点的方法

string filePath = System.IO.Path.GetFullPath(@"DB_Tax.INI");
            Read_INT read_ini = new Read_INT(filePath);
            string url = read_ini.ReadInivalue("webip", "server_web");

写入ini文件的方法和读取大同小异

原文地址:https://www.cnblogs.com/yuxuan/p/1858437.html