使用INI配置文件,简单便捷。

该辅助工具类为C#操作INI文件的辅助类,源码在某位师傅的基础上完善的来,因为忘记最初的来源了,因此不能提及引用,在此深感遗憾,并对贡献者表示感谢。

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text; namespace Eyuan.Common
{
public static class INIHelper
{ #region 读写INI文件相关
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Ansi)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Ansi)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernel32")]
private static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName); [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Ansi)]
private static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath); [DllImport("KERNEL32.DLL ", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Ansi)]
private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath);
#endregion #region 读写操作(字符串)
/// <summary>
/// 向INI写入数据
/// </summary>
/// <PARAM name="Section">节点名</PARAM>
/// <PARAM name="Key">键名</PARAM>
/// <PARAM name="Value">值(字符串)</PARAM>
public static void Write(string Section, string Key, string Value, string path)
{
WritePrivateProfileString(Section, Key, Value, path);
}
/// <summary>
/// 读取INI数据
/// </summary>
/// <PARAM name="Section">节点名</PARAM>
/// <PARAM name="Key">键名</PARAM>
/// <PARAM name="Path">值名</PARAM>
/// <returns>值(字符串)</returns>
public static string Read(string Section, string Key, string path)
{
StringBuilder temp = new StringBuilder();
int i = GetPrivateProfileString(Section, Key, "", temp, , path);
return temp.ToString();
}
#endregion #region 配置节信息
/// <summary>
/// 读取一个ini里面所有的节
/// </summary>
/// <param name="sections"></param>
/// <param name="path"></param>
/// <returns>-1:没有节信息,0:正常</returns>
public static int GetAllSectionNames(out string[] sections, string path)
{
int MAX_BUFFER = ;
IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
if (bytesReturned == )
{
sections = null;
return -;
}
string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
Marshal.FreeCoTaskMem(pReturnedString);
//use of Substring below removes terminating null for split
sections = local.Substring(, local.Length - ).Split('\0');
return ;
}
/// <summary>
/// 返回指定配置文件下的节名称列表
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static List<string> GetAllSectionNames(string path)
{
List<string> sectionList = new List<string>();
int MAX_BUFFER = ;
IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
if (bytesReturned != )
{
string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
Marshal.FreeCoTaskMem(pReturnedString);
sectionList.AddRange(local.Substring(, local.Length - ).Split('\0'));
}
return sectionList;
} /// <summary>
/// 得到某个节点下面所有的key和value组合
/// </summary>
/// <param name="section">指定的节名称</param>
/// <param name="keys">Key数组</param>
/// <param name="values">Value数组</param>
/// <param name="path">INI文件路径</param>
/// <returns></returns>
public static int GetAllKeyValues(string section, out string[] keys, out string[] values, string path)
{
byte[] b = new byte[];//配置节下的所有信息
GetPrivateProfileSection(section, b, b.Length, path);
string s = System.Text.Encoding.Default.GetString(b);//配置信息
string[] tmp = s.Split((char));//Key\Value信息
List<string> result = new List<string>();
foreach (string r in tmp)
{
if (r != string.Empty)
result.Add(r);
}
keys = new string[result.Count];
values = new string[result.Count];
for (int i = ; i < result.Count; i++)
{
string[] item = result[i].Split(new char[] { '=' });//Key=Value格式的配置信息
//Value字符串中含有=的处理,
//一、Value加"",先对""处理
//二、Key后续的都为Value
if (item.Length > )
{
keys[i] = item[].Trim();
values[i] = result[i].Substring(keys[i].Length + );
}
if (item.Length == )//Key=Value
{
keys[i] = item[].Trim();
values[i] = item[].Trim();
}
else if (item.Length == )//Key=
{
keys[i] = item[].Trim();
values[i] = "";
}
else if (item.Length == )
{
keys[i] = "";
values[i] = "";
}
}
return ;
}
/// <summary>
/// 得到某个节点下面所有的key
/// </summary>
/// <param name="section">指定的节名称</param>
/// <param name="keys">Key数组</param>
/// <param name="path">INI文件路径</param>
/// <returns></returns>
public static int GetAllKeys(string section, out string[] keys, string path)
{
byte[] b = new byte[]; GetPrivateProfileSection(section, b, b.Length, path);
string s = System.Text.Encoding.Default.GetString(b);
string[] tmp = s.Split((char));
ArrayList result = new ArrayList();
foreach (string r in tmp)
{
if (r != string.Empty)
result.Add(r);
}
keys = new string[result.Count];
for (int i = ; i < result.Count; i++)
{
string[] item = result[i].ToString().Split(new char[] { '=' });
if (item.Length == )
{
keys[i] = item[].Trim();
}
else if (item.Length == )
{
keys[i] = item[].Trim();
}
else if (item.Length == )
{
keys[i] = "";
}
}
return ;
}
/// <summary>
/// 获取指定节下的Key列表
/// </summary>
/// <param name="section">指定的节名称</param>
/// <param name="path">配置文件名称</param>
/// <returns>Key列表</returns>
public static List<string> GetAllKeys(string section, string path)
{
List<string> keyList = new List<string>();
byte[] b = new byte[];
GetPrivateProfileSection(section, b, b.Length, path);
string s = System.Text.Encoding.Default.GetString(b);
string[] tmp = s.Split((char));
List<string> result = new List<string>();
foreach (string r in tmp)
{
if (r != string.Empty)
result.Add(r);
}
for (int i = ; i < result.Count; i++)
{
string[] item = result[i].Split(new char[] { '=' });
if (item.Length == || item.Length == )
{
keyList.Add(item[].Trim());
}
else if (item.Length == )
{
keyList.Add(string.Empty);
}
}
return keyList;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="section"></param>
/// <param name="path"></param>
/// <returns></returns>
public static List<string> GetAllValues(string section, string path)
{
List<string> keyList = new List<string>();
byte[] b = new byte[];
GetPrivateProfileSection(section, b, b.Length, path);
string s = System.Text.Encoding.Default.GetString(b);
string[] tmp = s.Split((char));
List<string> result = new List<string>();
foreach (string r in tmp)
{
if (r != string.Empty)
result.Add(r);
}
for (int i = ; i < result.Count; i++)
{
string[] item = result[i].Split(new char[] { '=' });
if (item.Length == || item.Length == )
{
keyList.Add(item[].Trim());
}
else if (item.Length == )
{
keyList.Add(string.Empty);
}
}
return keyList;
} #endregion #region 通过值查找键(一个节中的键唯一,可能存在多个键值相同,因此反查的结果可能为多个) /// <summary>
/// 第一个键
/// </summary>
/// <param name="section"></param>
/// <param name="path"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string GetFirstKeyByValue(string section, string path, string value)
{
foreach (string key in GetAllKeys(section, path))
{
if (ReadString(section, key, "", path) == value)
{
return key;
}
}
return string.Empty;
}
/// <summary>
/// 所有键
/// </summary>
/// <param name="section"></param>
/// <param name="path"></param>
/// <param name="value"></param>
/// <returns></returns>
public static List<string> GetKeysByValue(string section, string path, string value)
{
List<string > keys = new List<string>();
foreach (string key in GetAllKeys(section, path))
{
if (ReadString(section, key, "", path) == value)
{
keys.Add(key);
}
}
return keys;
}
#endregion #region 具体类型的读写 #region string
/// <summary>
///
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="defaultValue" />
/// <param name="path"></param>
/// <returns></returns>
public static string ReadString(string sectionName, string keyName, string defaultValue, string path)
{
const int MAXSIZE = ;
StringBuilder temp = new StringBuilder(MAXSIZE);
GetPrivateProfileString(sectionName, keyName, defaultValue, temp, , path);
return temp.ToString();
} /// <summary>
///
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="value"></param>
/// <param name="path"></param>
public static void WriteString(string sectionName, string keyName, string value, string path)
{
WritePrivateProfileString(sectionName, keyName, value, path);
}
#endregion #region Int
/// <summary>
///
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="defaultValue"></param>
/// <param name="path"></param>
/// <returns></returns>
public static int ReadInteger(string sectionName, string keyName, int defaultValue, string path)
{ return GetPrivateProfileInt(sectionName, keyName, defaultValue, path); }
/// <summary>
///
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="value"></param>
/// <param name="path"></param>
public static void WriteInteger(string sectionName, string keyName, int value, string path)
{ WritePrivateProfileString(sectionName, keyName, value.ToString(), path); }
#endregion #region bool
/// <summary>
/// 读取布尔值
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="defaultValue"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool ReadBoolean(string sectionName, string keyName, bool defaultValue, string path)
{ int temp = defaultValue ? : ; int result = GetPrivateProfileInt(sectionName, keyName, temp, path); return (result == ? false : true); }
/// <summary>
/// 写入布尔值
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="value"></param>
/// <param name="path"></param>
public static void WriteBoolean(string sectionName, string keyName, bool value, string path)
{
string temp = value ? "1 " : "0 ";
WritePrivateProfileString(sectionName, keyName, temp, path);
}
#endregion #endregion #region 删除操作
/// <summary>
/// 删除指定项
/// </summary>
/// <param name="sectionName"></param>
/// <param name="keyName"></param>
/// <param name="path"></param>
public static void DeleteKey(string sectionName, string keyName, string path)
{
WritePrivateProfileString(sectionName, keyName, null, path);
} /// <summary>
/// 删除指定节下的所有项
/// </summary>
/// <param name="sectionName"></param>
/// <param name="path"></param>
public static void EraseSection(string sectionName, string path)
{
WritePrivateProfileString(sectionName, null, null, path);
}
#endregion #region 判断节、键是否存在
/// <summary>
/// 指定节知否存在
/// </summary>
/// <param name="section"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool ExistSection(string section, string fileName)
{
string[] sections = null;
GetAllSectionNames(out sections, fileName);
if (sections != null)
{
foreach (var s in sections)
{
if (s == section)
{
return true;
}
}
}
return false;
}
/// <summary>
/// 指定节下的键是否存在
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool ExistKey(string section, string key, string fileName)
{
string[] keys = null;
GetAllKeys(section, out keys, fileName);
if (keys != null)
{
foreach (var s in keys)
{
if (s == key)
{
return true;
}
}
}
return false;
}
#endregion #region 同一Section下添加多个Key\Value
/// <summary>
///
/// </summary>
/// <param name="section"></param>
/// <param name="keyList"></param>
/// <param name="valueList"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool AddSectionWithKeyValues(string section, List<string> keyList, List<string> valueList, string path)
{
bool bRst = true;
//判断Section是否已经存在,如果存在,返回false
//已经存在,则更新
//if (GetAllSectionNames(path).Contains(section))
//{
// return false;
//}
//判断keyList中是否有相同的Key,如果有,返回false //添加配置信息
for (int i = ; i < keyList.Count; i++)
{
WriteString(section, keyList[i], valueList[i], path);
}
return bRst;
}
#endregion
}
}

IniHelper——INI操作辅助类的更多相关文章

  1. winform INI文件操作辅助类

    using System;using System.Runtime.InteropServices;using System.Text; namespace connectCMCC.Utils{ // ...

  2. 我也分享一个c# ini操作类

    刚刚看了一篇 @云菲菲 的关于基于正则的INI辅助类文章:http://www.cnblogs.com/yunfeifei/p/4081977.html,作者写的不错.还看到评论处有一个的地址:htt ...

  3. DateHelper.cs日期时间操作辅助类C#

    //==================================================================== //** Copyright © classbao.com ...

  4. 【转载】C#工具类:FTP操作辅助类FTPHelper

    FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...

  5. JAVA 图像操作辅助类

    package util; import java.awt.Component; import java.awt.Image; import java.awt.MediaTracker; import ...

  6. Java常用工具类之数据库操作辅助类DBUtil.java

    package com.qushida.util; import java.beans.BeanInfo; import java.beans.Introspector; import java.be ...

  7. C# 配置文件ini操作类

    // [ DllImport ( "kernel32" ) ] //private static extern long WritePrivateProfileString ( s ...

  8. ini操作

    关于C#操作INI文件的总结 INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下: [Section1] key = value2 key = value2 …… [Sectio ...

  9. .NET中Redis安装部署及使用方法简介附->开源Redis操作辅助类

    Redis是一个用的比较广泛的Key/Value的内存数据库,新浪微博.Github.StackOverflow 等大型应用中都用其作为缓存,Redis的官网为http://redis.io/. Re ...

随机推荐

  1. C++中指针运算

    1,指针可以和数字运算,指针+-整数,如, int num[] = {1,2,3,4,5,6,7,8}; int *p = num; p++; p--; p = p + 3; p = p -3; 数字 ...

  2. SpringBoot 整合 中国移动 MAS HTTP1.0 实现短信发送服务

    因为客户需要,本身使用的 阿里云的短信服务改为了中国移动MAS HTTP 1.0  短信通知,因为看到网络上关于此类的博客知识很少,再趟完坑后特地写下这篇博客,提醒后来人. 特别感谢 中国移动MAS ...

  3. Apache Maven的入门使用之项目的基本构建(1)

    前言 最近在研究java框架struts2的相关漏洞,然后就去看了官方给出的文档.在看文档的过程中发现使用到了Apache Maven这个项目管理工具,我在网上搜索了一下,大多数文章都写得不是很系统, ...

  4. Openerp 修改 tree view 的列宽

    在 tree 的后边添加自定义css 列:“my_class" 然后在对应的css文件中,添加样式: 保存,重新刷新页面即可.

  5. 在linux上安装 sql server for linux

    在linux上安装 sql server for linux Install SQL Server on Red Hat Enterprise Linux Install SQL Server To ...

  6. springmvc执行原理及自定义mvc框架

    springmvc是spring的一部分,也是一个优秀的mvc框架,其执行原理如下: (1)浏览器提交请求经web容器(比如tomcat)转发到中央调度器dispatcherServlet. (2)中 ...

  7. C# 委托的一些使用上的小技巧

    1.委托是一种数据类型,我们可以在任何定义类的地方定义委托,在任何声明类的地方声明委托 2.初始化委托有两种方式,代码如下: (1).像类一样初始化委托 public delegate void Sa ...

  8. CentOS7编译curl

    1.下载curl源代码 https://curl.haxx.se/download.html 2.进入curl目录 ./configure --prefix=/usr/local/curl make ...

  9. Java的三个基础排序算法(其余将在以后补充)

    第一个:冒泡排序算法 原理:相邻的两个值进行比较,如果前面的比后面的大就交换位置 eg:假设有5个元素的一个array 第一次:会比较4次,将最大的值放在最右边 第二次:会比较3次,又排出剩余4个元素 ...

  10. linux主机名莫名其妙变成了bogon,并解决修改为localhost

    起因:公司网络接口做了接口认证,虚拟机桥接至物理网卡无法完成认证进行网络访问,无奈之下只能讲虚拟机网络模式更改为NAT模式,更改完成之后进行ssh登录,发现主机名发生了变化. 更改NAT模式之前 [r ...