您现在的位置是:首页 >其他 >c#INI配置文件的读取写入网站首页其他
c#INI配置文件的读取写入
简介c#INI配置文件的读取写入
INI配置文件的读取写入
在上位机程序开发或者其他软件开发当中,通常用户需要对部分功能设置做保存。
例如打印报表功能,用户在勾选需要打印报表选框之后,如果退出重启软件而需要重新勾选的话就不太方便。所以需要对当前是否勾选做保存,然而在软件关闭重启的过程中,所有的变量都会被初始化,这个时候就需要把功能是否勾选这个变量写在程序外部,这里演示用INI配置文件来完成这个操作。
- IniGet.cs文件如下
- 这个文件作用在于引用配置文件的库,同时定义配置文件的读取写入格式,只需要添加进项目里就可以使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace getini
{
public class IniGet
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);
private string ReadString(string section, string key, string def, string filePath)
{
StringBuilder temp = new StringBuilder(1024);
try
{
GetPrivateProfileString(section, key, def, temp, 1024, filePath);
}
catch
{ }
return temp.ToString();
}
public void INIWrite(string section, string key, string value, string path)
{
//section=配置节点名称,key=键名,value=返回键值,path=路径
WritePrivateProfileString(section, key, value, path);
}
public Dictionary<string, string> ReadIniAllKeys(string section, string filePath)
{
UInt32 MAX_BUFFER = 32767;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string[] items = new string[0];
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath);
if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
{
string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
items = returnedString.Split(new char[] { '