using System.IO;
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// 读取ini配置文件
/// [Time]
/// time=10
/// [Speed]
/// speed=5
/// ConfigIni ini=new ConfigIni(Application.StreamingAssets+"/Setting.ini");
/// time=ini.ReadIniContent("Time","time");
/// speed=ini.ReadIniContent("Speed","speed");
/// ini.WritePrivateProfileString("Count","count","5");
/// </summary>
public class ConfigIni
{
public string path;
//ini文件的路径
public ConfigIni(string path)
{
this.path = path;
}
//这个读取中文路径的报错
/*
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string value, string path);
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string deval, StringBuilder stringBuilder, int size, string path);
[DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr handle, String message, String title, int type);
*/
//这个可以读取中文路径的
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool WritePrivateProfileString(
string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetPrivateProfileString(
string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
int nSize, string lpFileName);
//写入ini文件
public void WriteIniContent(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.path);
}
//读取Ini文件
public string ReadIniContent(string section, string key)
{
StringBuilder temp = new StringBuilder(2550);
int i = GetPrivateProfileString(section, key, "", temp, 2550, this.path);
//MessageBox(IntPtr.Zero, this.path+i + ","+temp+","+section+key, "ReadIniContent", 0);
return temp.ToString();
}
//判断路径是否正确
public bool IsIniPath()
{
return File.Exists(this.path);
}
}
读取测试:
string configPath = Application.streamingAssetsPath + "\\config.ini";
ConfigIni configIni = new ConfigIni(configPath);
string str = configIni.ReadIniContent("para", "minNum");
int num = Convert.ToInt32(str);