日期:2011-07-13 浏览次数:20485 次
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();