第一种方法:
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:日志相关的工具类
*│ 作 者:执笔小白
*│ 版 本:1.0
*│ 创建时间:2020-6-13 15:40:56
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: ZhibiXiaobai.Uril.ConfigFileHelper
*│ 类 名:OperateFile_InI
*└──────────────────────────────────────────────────────────────┘
*/
using System.Runtime.InteropServices;
using System.Text;
namespace ZhibiXiaobai.Uril.ConfigFileHelper
{
/// <summary>
/// InI文件的读写
/// </summary>
public class OperateFile_InI
{
#region API函数声明
/// <summary>
/// 读-获取所有节点名称(Section)
/// </summary>
/// <param name="lpszReturnBuffer">存放节点名称的内存地址,每个节点之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);
/// <summary>
/// 读-获取某个指定节点(Section)中所有KEY和Value
/// </summary>
/// <param name="lpAppName">节点名称</param>
/// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);
/// <summary>
/// 写-将指定的键值对写到指定的节点,如果已经存在则替换。
/// </summary>
/// <param name="lpAppName">节点,如果不存在此节点,则创建此节点</param>
/// <param name="lpString">Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
/// <para>如果为string.Empty,则删除指定节点下的所有内容,保留节点</para>
/// <para>如果为null,则删除指定节点下的所有内容,并且删除该节点</para>
/// </param>
/// <param name="lpFileName">INI文件</param>
/// <returns>是否成功写入</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)] //可以没有此行
private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);
/// <summary>
/// 写-写标签值
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">Key</param>
/// <param name="val"></param>
/// <param name="filePath">Ini文件</param>
/// <returns></returns>
[DllImport("kernel32", EntryPoint = "WritePrivateProfileString")] // 返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);
/// <summary>
/// 读-读标签值
/// </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", EntryPoint = "GetPrivateProfileString")] // 返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);
#endregion API函数声明
#region 读Ini文件
/// <summary>
/// 读Ini文件-标签值
/// 详细见INI例子
/// </summary>
/// <param name="Section">[Section]标签的名字</param>
/// <param name="Key">key</param>
/// <param name="NoText">未找到值时默认返回的值</param>
/// <param name="iniFilePath">ini文件的路径</param>
/// <returns></returns>
public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
return temp.ToString();
}
else
{
return String.Empty;
}
}
/// <summary>
/// 读取INI文件中指定INI文件中的所有节点名称(Section)-未测试多线程使用
/// 最多32767个char
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <returns>所有节点,没有内容返回string[0]</returns>
public static string[] INIGetAllSectionNames(string iniFile)
{
uint MAX_BUFFER = 32767; //默认为32767
string[] sections = new string[0]; //返回值
//申请内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
if (bytesReturned != 0)
{
//读取指定内存的内容
string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
//每个节点之间用\0分隔,末尾有一个\0
sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
//释放内存
Marshal.FreeCoTaskMem(pReturnedString);
return sections;
}
/// <summary>
/// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)-未测试多线程使用
/// 最多32767个char
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <param name="section">节点名称</param>
/// <returns>指定节点中的所有项目,没有内容返回string[0]</returns>
public static string[] INIGetAllItems(string iniFile, string section)
{
//返回值形式为 key=value,例如 Color=Red
uint MAX_BUFFER = 32767; //默认为32767
string[] items = new string[0]; //返回值
//分配内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile);
if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
{
string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
Marshal.FreeCoTaskMem(pReturnedString); // 释放内存
return items;
}
#endregion 读
#region 写Ini文件
/// <summary>
/// 写Ini文件-标签值
/// 详细见INI例子
/// </summary>
/// <param name="Section">[Section]标签的名字</param>
/// <param name="Key">key</param>
/// <param name="Value">key对应的Value</param>
/// <param name="iniFilePath">ini文件的路径</param>
/// <returns></returns>
public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
return OpStation == 0 ? false : true;
}
else
{
return false;
}
}
#endregion 写
}
/* DBServer.ini结构如下
* [Head]
* Head=Head项不可删除
* [Server]
* Name=localhost
* [DB]
* Name=NorthWind
* [User]
* Name=sa
*/
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
- 135.
- 136.
- 137.
- 138.
- 139.
- 140.
- 141.
- 142.
- 143.
- 144.
- 145.
- 146.
- 147.
- 148.
- 149.
- 150.
- 151.
- 152.
- 153.
- 154.
- 155.
- 156.
- 157.
- 158.
- 159.
- 160.
- 161.
- 162.
- 163.
- 164.
- 165.
- 166.
- 167.
- 168.
- 169.
- 170.
- 171.
- 172.
- 173.
- 174.
- 175.
- 176.
- 177.
- 178.
- 179.
- 180.
- 181.
- 182.
- 183.
- 184.
- 185.
- 186.
- 187.
- 188.
- 189.
- 190.
- 191.
- 192.
- 193.
- 194.
- 195.
- 196.
- 197.
- 198.
- 199.
- 200.
- 201.
- 202.
- 203.
- 204.
- 205.
- 206.
- 207.
- 208.
- 209.
第二种方法:
微软的Configuration Extensions来读取ini文件。
第三种方法:
同事写的文件流读取的方法:
查看代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace BOZHON.TSAMO.Common.文件操作类
{
/// <summary>
/// 仅支持整个程序读取单个文件,有需要可自己修改
/// </summary>
public class ReadIniFileHelper
{
private static Dictionary<string, Dictionary<string, string>> IniFileContent;
public static string message;
/// <summary>
/// 初始化读取
/// </summary>
/// <param name="path">文件路径</param>
public static void InitializeRead(string path)
{
IniFileContent = new Dictionary<string, Dictionary<string, string>>();
if (!File.Exists(path))
{
message = "文件路径不存在";
return;
}
try
{
string[] lines = File.ReadAllLines(path).Select(a => a.Trim()).ToArray();
Dictionary<string, string> keyValues = null;
string key = null;
for (int i = 0; i < lines.Length; i++)
{
string item = lines[i];
if (string.IsNullOrEmpty(item))
{
continue;
}
try
{
if (item.First() == '[' && item.Last() == ']')
{
key = item.Substring(1, item.Length - 2);
keyValues = new Dictionary<string, string>();
IniFileContent.Add(key, keyValues);
}
else
{
keyValues = IniFileContent[key];
var array = item.Split('=');
keyValues.Add(array[0], array[1]);
}
}
catch
{
IniFileContent = null;
message = $"第{i + 1}行解析异常";
return;
}
}
message = null;
}
catch (Exception e)
{
IniFileContent = null;
message = e.ToString();
return;
}
}
/// <summary>
/// 指定读取
/// </summary>
/// <param name="section"></param>
/// <returns>字典</returns>
public static Dictionary<string, string> ReadValue(string section)
{
if (string.IsNullOrEmpty(section))
{
message = "参数为空";
return null;
}
if (IniFileContent == null)
{
message = "请先执行【InitializeRead】方法";
return null;
}
if (!IniFileContent.ContainsKey(section))
{
message = "数据不存在";
return null;
}
message = null;
return IniFileContent[section];
}
/// <summary>
/// 指定读取
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns>字符串</returns>
public static string ReadValue(string section, string key)
{
if (string.IsNullOrEmpty(section) || string.IsNullOrEmpty(key))
{
message = "参数为空";
return null;
}
if (IniFileContent == null)
{
message = "请先执行【InitializeRead】方法";
return null;
}
if (!IniFileContent.ContainsKey(section))
{
message = "数据不存在";
return null;
}
message = null;
return IniFileContent[section][key];
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
作者:꧁执笔小白꧂