We need to use API functions to read INI files.
1. Create a P/Invoke application class
Find the Win32 API defined in C # In pinvoke.net.
API for reading INI files: GetPrivateProfileString <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> [DllImport ("kernel32.dll", CharSet = CharSet. unicode)] static extern uint GetPrivateProfileString (string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName );Note: The DllImport attribute comes from using System. Runtime. InteropServices;
(1) lpAppName
Section name
(2) lpKeyName
Key name
(3) lpDefault
Default Value
(4) lpReturnedString
Return Value
(5) nSize
Return Value Length
(6) lpFileName
Name of the file to be read
Create a public method for the program to use.
public string readIniFileVal(string iniFileName, string section, string key) { StringBuilder retStrBuilder = new StringBuilder(256); GetPrivateProfileString( section, key, "", retStrBuilder, 256, iniFileName); return retStrBuilder.ToString(); }
Cwin32API. cs
using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace callXBFLibrary{ class Cwin32API { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern uint GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); public string readIniFileVal(string iniFileName, string section, string key) { StringBuilder retStrBuilder = new StringBuilder(256); GetPrivateProfileString( section, key, "", retStrBuilder, 256, iniFileName); return retStrBuilder.ToString(); } } }