一、首先在项目解决方案内新添加一个类,命名为iniFile.cs
1. 添加以下头文件
using System.IO;
using System.Runtime.InteropServices;
2. 定义一个全局变量路径字符串来传递路径,改路径存储的是将要读取或者写入ini文件的位置
public string path;
3. 引入kernel32.dll这个动态连接库,该动态连接库里面包含了很多WindowsAPI函,
1)继承dll文件函数的写入
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
2)继承dll文件函数的读取
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="def"></param>
/// <param name="retVal"></param>
/// <param name="size"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
4. ini文件构造器
/// <param name="INIPath"></param>
public IniFile(string INIPath)
{
path = INIPath;
}
5. 向ini文件写入数据,其中section为段名,key为键名,value为键对应的值
/// <param name="Section"></param>
/// <param name="Key"></param>
/// <param name="Value"></param>
public void WriteString(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.path);
}
/// <param name="Section"></param>
/// <param name="Key"></param>
/// <param name="Path"></param>
/// <returns></returns>
public string ReadString(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
return temp.ToString();
}
二、代码举例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace Code
{
static void Main()
{
iniFile _file;
WriteProfile();
Console.WriteLine(ReadProfile());
public string ReadProfile()
{
//FilePath = %Project Path%\%Proje Name%\bin\Debug
string strPath = AppDomain.CurrentDomain.BaseDirectory;
_file = new iniFile(strPath + "SerialPortData.ini");
string _str1 = _file.ReadString("Section1", "Key1");
string _str2 = _file.ReadString("Section1", "Key2");
string _str3 = _file.ReadString("Section2", "Key1");
string _str4 = _file.ReadString("Section2", "Key2");
return _str1 + _str2 + _str3 + _str4;
}
public void WriteProfile()
{
string strPath = AppDomain.CurrentDomain.BaseDirectory;
_file = new iniFile(strPath + "SerialPortData.ini");
_file.WriteString("Section1", "Key1", "111");
_file.WriteString("Section1", "Key2", "222");
_file.WriteString("Section2", "Key1", "333");
_file.WriteString("Section2", "Key2", "444");
}
}
}