[WPF]C#读写ini配置文件
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-22 21:30:48
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
使用ini配置文件保存一些数据
OperateIniFile.cs
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Ank.Class
{
public class OperateIniFile
{
#region API函数声明
[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);
#endregion
#region 读Ini文件
public static string read(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;
}
}
#endregion
#region 写Ini文件
public static bool write(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;
}
}
#endregion
}
}