C#操作INI配置文件
旧文章数据恢复-来自有道云笔记
在很多的程序中,我们都会看到有以.ini为后缀名的文件,这个文件可以很方便的对程序配置的一些信息进行设置和读取,比如说我们在做一个程序后台登陆的时候,需要自动登录或者是远程配置数据库连接,及保存密码设置等等
此文章仅在C# winform程序中进行写入和读取操作。
为了方便起见,现在以一个简单的小实例来对C#操作INI配置文件进行讲解:
窗体的大致布局如下:
当点击写入按钮的时候就会把文本框中输入的值写入到INI文件配置中,结果会如图所示:
当点击读取按钮的时候就会把INI文件中的节点信息的值填充到窗体中的文本框中:
以上就是用C#操作INI文件的整个流程,现在来介绍后台代码是怎样实现的:
在项目名称空间的上方要添加以下的引用:
using System.Runtime.InteropServices; //调用系统DLL using System.IO; //读写文件
再调用一些系统函数的变量,代码如下:
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="section">节点名称[如[TypeName]]</param>
/// <param name="key">键</param>
/// <param name="val">值</param>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);
/// <summary>
/// 读取INI文件
/// </summary>
/// <param name="section">节点名称</param>
/// <param name="key">键</param>
/// <param name="def">值</param>
/// <param name="retval">stringbulider对象</param>
/// <param name="size">字节大小</param>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filePath);声明INI配置文件路径和节点名称:private string strFilePath = Application.StartupPath + "\\Settings.ini"; //INI文件路径名 private string strSec = "Settings"; //节点名称
写入INI配置文件(INI配置文件是放在程序的Debug文件夹下的):
// 写入文件
private void btnWrite_Click(object sender, EventArgs e)
{
try
{
//根据INI文件名设置要写入INI文件的节点名称
//此处的节点名称完全可以根据实际需要进行配置
strSec = Path.GetFileNameWithoutExtension(strFilePath);
WritePrivateProfileString(strSec, "Name", txtName.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "Sex", txtSex.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "Age", txtAge.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "Address", txtAddress.Text.Trim(), strFilePath);
MessageBox.Show("写入成功");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
读取INI配置文件:
// 读取INI文件
private void btnRead_Click(object sender, EventArgs e)
{
if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
{
strSec = Path.GetFileNameWithoutExtension(strFilePath);
txtName.Text = ContentValue(strSec, "Name");
txtSex.Text = ContentValue(strSec, "Sex");
txtAge.Text = ContentValue(strSec, "Age");
txtAddress.Text = ContentValue(strSec, "Address");
}
else
{
MessageBox.Show("INI文件配置不存在");
}
}
在读取的时候用到了自定义读取函数的方法,在该方法中调用了系统函数
/// <summary>
/// 自定义读取INI文件中的内容方法
/// </summary>
/// <param name="Section">键</param>
/// <param name="key">值</param>
/// <returns></returns>
private string ContentValue(string Section,string key)
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
return temp.ToString();
}
示例源码下载:
本文标题:C#操作INI配置文件
本文链接:https://www.fghrsh.net/post/14.html
版权声明:本文使用「署名-非商业性使用-相同方式共享 4.0 国际」创作共享协议,转载或使用请遵守署名协议。

博主是计算机天才啊