废话不多说,直接上代码
1:引入命名空间
System.Runtime.InteropServices
System.IO
2:写一个类 iniHelper
public class IniHelper
{
[DllImport("kernel32")]//返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]//返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// 读取ini文件
/// </summary>
/// <param name="Section">名称</param>
/// <param name="Key">关键字</param>
/// <param name="defaultText">默认值</param>
/// <param name="iniFilePath">ini文件地址</param>
/// <returns></returns>
public static string GetValue(string Section, string Key, string defaultText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, defaultText, temp, 1024, iniFilePath);
return temp.ToString();
}
else
{
return defaultText;
}
}
/// <summary>
/// 写入ini文件
/// </summary>
/// <param name="Section">名称</param>
/// <param name="Key">关键字</param>
/// <param name="defaultText">默认值</param>
/// <param name="iniFilePath">ini文件地址</param>
/// <returns></returns>
public static bool SetValue(string Section, string Key, string Value, string iniFilePath)
{
var pat = Path.GetDirectoryName(iniFilePath);
if (Directory.Exists(pat) == false)
{
Directory.CreateDirectory(pat);
}
if (File.Exists(iniFilePath) == false)
{
File.Create(iniFilePath).Close();
}
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
{
return false;
}
else
{
return true;
}
}
}
5:可以手动新建ini文件,也可自动创建ini文件,博=主比较懒,直接手动创建的
我ini文件是这样配置的:
[我的数据]
MyID=9527
4:直接调用
string MyID = Console.ReadLine();
//写入文件
string file = System.Environment.CurrentDirectory + @"\config.ini";
if (file!=null)
{
IniHelper.SetValue("我的数据", "MyID", MyID, file);
}
Console.WriteLine("我输入的ID为{0}",MyID);
//读取文件
if (file != null)
{
MyID = IniHelper.GetValue("我的数据", "MyID", "", file);
Console.WriteLine("我读取到的ID为{0}"+MyID);
Console.ReadLine();
}