using system;
using system.text;
using system.io;
using system.runtime.interopservices;
using system.collections.generic;
public class operateinifile
{
private static string filepath = "";
#region api函数声明
[dllimport("kernel32")]
private static extern long writeprivateprofilestring(string section, string key,
string val, string filepath);
//需要调用getprivateprofilestring的重载
[dllimport("kernel32", entrypoint = "getprivateprofilestring")]
private static extern long getprivateprofilestring(string section, string key,
string def, stringbuilder retval, int size, string filepath);
[dllimport("kernel32", entrypoint = "getprivateprofilestring")]
private static extern uint getprivateprofilestringa(string section, string key,
string def, byte[] retval, int size, string filepath);
#endregion
public static list<string> readsections()
{
return readsections(filepath);
}
public static list<string> readsections(string inifilename)
{
list<string> result = new list<string>();
byte[] buf = new byte[65536];
uint len = getprivateprofilestringa(null, null, null, buf, buf.length, inifilename);
int j = 0;
for (int i = 0; i < len; i++)
if (buf[i] == 0)
{
result.add(encoding.default.getstring(buf, j, i - j));
j = i + 1;
}
return result;
}
public static list<string> readkeys(string sectionname)
{
return readkeys(sectionname, filepath);
}
public static list<string> readkeys(string sectionname, string inifilename)
{
list<string> result = new list<string>();
byte[] buf = new byte[65536];
uint len = getprivateprofilestringa(sectionname, null, null, buf, buf.length, inifilename);
int j = 0;
for (int i = 0; i < len; i++)
if (buf[i] == 0)
{
result.add(encoding.default.getstring(buf, j, i - j));
j = i + 1;
}
return result;
}
public static void setfilepath(string filepath)
{
filepath = filepath;
}
#region 读ini文件
public static string readinidata(string section, string key, string notext)
{
return readinidata(section, key, notext, filepath);
}
public static string readinidata(string section, string key, string notext, string inifilepath)
{
if (file.exists(inifilepath))
{
stringbuilder temp = new stringbuilder(1024);
getprivateprofilestring(section, key, notext, temp, 1024, inifilepath);
return temp.tostring();
}
elsereturn string.empty;
}
#endregion
#region 写ini文件
public static bool writeinidata(string section, string key, string value)
{
return writeinidata(section, key, value, filepath);
}
public static bool writeinidata(string section, string key, string value, string inifilepath)
{
if (file.exists(inifilepath))
{
long opstation = writeprivateprofilestring(section, key, value, inifilepath);
if (opstation == 0)
return false;
elsereturn true;
}
elsereturn false;
}
#endregion
}
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!