using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
namespace ReadWriteINI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("kernel32")]
private static extern int GetPrivateProfileInt(
string lpApplicationName,
string lpKeyName,
int nDefault,
string lpFileName);
[DllImport("kernel32")]
private static extern bool GetPrivateProfileString(
string lpApplicationName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
int nSize,
string lpFileName);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpApplicationName,
string lpKeyName,
string lpString,
string lpFileName);
[DllImport("kernel32")]
private static extern bool GetPrivateProfileSection(
string lpAppName,
StringBuilder lpReturnedString,
int nSize,
string lpFileName);
[DllImport("kernel32")]
private static extern bool WritePrivateProfileSection(
string lpAppName,
string lpString,
string lpFileName);
public static string FILE_NAME;
private void Form1_Load(object sender, EventArgs e)
{
FILE_NAME = Application.StartupPath + "//test.ini";
if (File.Exists(FILE_NAME))
{
StringBuilder strCaption = new StringBuilder(256);
GetPrivateProfileString("Form", "Caption", "Default Caption",
strCaption,
strCaption.Capacity,
FILE_NAME);
this.Text = strCaption.ToString();
int myWidth = GetPrivateProfileInt("Form", "Width", this.Width, FILE_NAME);
this.Width = myWidth;
int myHeight = GetPrivateProfileInt("Form", "Height", this.Height, FILE_NAME);
this.Height = myHeight;
int myLeft = GetPrivateProfileInt("Form", "Left", this.Left, FILE_NAME);
this.Left = myLeft;
int myTop = GetPrivateProfileInt("Form", "Top", this.Top, FILE_NAME);
this.Top = myTop;
}
}
private void button1_Click(object sender, EventArgs e)
{
string strCaption = this.Text;
WritePrivateProfileString("Form", "Caption", strCaption, FILE_NAME);
WritePrivateProfileString("Form", "Width", this.Width.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Hight", this.Height.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Left", this.Left.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Top", this.Top.ToString(), FILE_NAME);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string strCaption = this.Text;
WritePrivateProfileString("Form", "Caption", strCaption, FILE_NAME);
WritePrivateProfileString("Form", "Width", this.Width.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Hight", this.Height.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Left", this.Left.ToString(), FILE_NAME);
WritePrivateProfileString("Form", "Top", this.Top.ToString(), FILE_NAME);
}
}
}
上面是C#中读写INI文件的一个范例代码,关键函数是在类定义那一段,那些函数仅作为声明,无需用户定义,它们也是固定的,可以满足基本的INI读写操作。
INI设置可以保存用户对于程序设置的修改等,可以防止系统设置出现空白而导致的错误。