c#中没有读写ini文件的类,但用api函数很容易实现.
窗体代码如下:
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
namespace inifiledemo
{
public partial class form1 : form
{
/**//**//**//// <summary>
/// 读ini文件文件api函数声明
/// </summary>
/// <param name="section">小节名</param>
/// <param name="key">关键字</param>
/// <param name="def">如果没找到时的默认值</param>
/// <param name="retval">存放返回值的缓冲区</param>
/// <param name="size">缓冲区大小</param>
/// <param name="filepath">要读取的ini文件的路径</param>
/// <returns>返回读取到的字符数</returns>
[dllimport("kernel32")]
private static extern long getprivateprofilestring(string section, string key, string def, stringbuilder retval, int size, string filepath);
/**//**//**//// <summary>
/// 写ini文件api函数声明
/// </summary>
/// <param name="section">小节名</param>
/// <param name="key">关键字</param>
/// <param name="val">要写入的值</param>
/// <param name="filepath">要写入的ini文件的路径</param>
/// <returns>返回写入的字符数</returns>
[dllimport("kernel32")]
private static extern long writeprivateprofilestring(string section, string key, string val, string filepath);
public form1()
{
initializecomponent();
}
/**//**//**//// <summary>
/// 从ini文件读取值并应用到窗体的width,height属性
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void form1_load(object sender, eventargs e)
{
stringbuilder mybuilder=new stringbuilder(256);
getprivateprofilestring("settings", "width", "300", mybuilder, 256, ".app.ini");
width = int32.parse(mybuilder.tostring());
textbox1.text = width.tostring();
getprivateprofilestring("settings", "height", "300", mybuilder, 256, ".app.ini");
height = int32.parse(mybuilder.tostring());
textbox2.text = height.tostring();
}
/**//**//**//// <summary>
/// 将自定义的值写入ini文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_click(object sender, eventargs e)
{
width = int32.parse(textbox1.text);
height = int32.parse(textbox2.text);
writeprivateprofilestring("settings", "width", textbox1.text, ".app.ini");
writeprivateprofilestring("settings", "height", textbox2.text, ".app.ini");
}
}
}
新闻热点
疑难解答