1、使用WindowsAPI函数实现
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace MyINI
{
class IniFile
{
string Path;
string EXE = Assembly.GetExecutingAssembly().GetName().Name;
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);
public IniFile(string IniPath = null)
{
Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
}
public string Read(string Key, string Section = null)
{
var RetVal = new StringBuilder(255);
GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
return RetVal.ToString();
}
public void Write(string Key, string Value, string Section = null)
{
WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
}
public void DeleteKey(string Key, string Section = null)
{
Write(Key, null, Section ?? EXE);
}
public void DeleteSection(string Section = null)
{
Write(null, null, Section ?? EXE);
}
public bool KeyExists(string Key, string Section = null)
{
return Read(Key, Section).Length > 0;
}
}
}
调用方法:
1)通过以下三种方式之一打开 INI 文件
//在与可执行文件相同的目录中创建或加载INI文件
//命名为EXE.ini(其中EXE是可执行文件的名称)
var MyIni = new IniFile();
//或在当前目录中指定一个配置文件的名称
var MyIni = new IniFile("Settings.ini");
// 或者在指定的目录中指定一个配置文件的名称
var MyIni = new IniFile(@"C:\Settings.ini");
2)写入配置
MyIni.Write("SiteName", "cjavapy");
MyIni.Write("Url", "https://www.cjavapy.com");
写入的内容如下:
[MyINI]
SiteName=cjavapy
Url=https://www.cjavapy.com
3)从 INI 文件中读取值
var siteName = MyIni.Read("SiteName");
var url = MyIni.Read("Url");
4)写入配置时指下配置项:
MyIni.Write("SiteName", "cjavapy", "MyWeb");
MyIni.Write("Url", "https://www.cjavapy.com", "MyWeb");
写入的内容如下:
[MyINI]
SiteName=cjavapy
Url=https://www.cjavapy.com
[MyWeb]
SiteName=cjavapy
Url=https://www.cjavapy.com
5)判断配置是否存在
if(!MyIni.KeyExists("Remark", "Audio"))
{
MyIni.Write("Remark", "Note", "Audio");
}
6)删除配置Key
MyIni.DeleteKey("Remark", "Audio");
7)删除配置项
MyIni.DeleteSection("MyWeb");
2、使用自定义类实现
using System;
using System.IO;
using System.Collections;
public class IniParser
{
private Hashtable keyPairs = new Hashtable();
private String iniFilePath;
private struct SectionPair
{
public String Section;
public String Key;
}
/// <summary>
/// 在给定的路径上打开INI文件并枚举IniParser中的值。
/// </summary>
/// <param name="iniPath">Full path to INI file.</param>
public IniParser(String iniPath)
{
TextReader iniFile = null;
String strLine = null;
String currentRoot = null;
String[] keyPair = null;
iniFilePath = iniPath;
if (File.Exists(iniPath))
{
try
{
iniFile = new StreamReader(iniPath);
strLine = iniFile.ReadLine();
while (strLine != null)
{
strLine = strLine.Trim().ToUpper();
if (strLine != "")
{
if (strLine.StartsWith("[") && strLine.EndsWith("]"))
{
currentRoot = strLine.Substring(1, strLine.Length - 2);
}
else
{
keyPair = strLine.Split(new char[] { '=' }, 2);
SectionPair sectionPair;
String value = null;
if (currentRoot == null)
currentRoot = "ROOT";
sectionPair.Section = currentRoot;
sectionPair.Key = keyPair[0];
if (keyPair.Length > 1)
value = keyPair[1];
keyPairs.Add(sectionPair, value);
}
}
strLine = iniFile.ReadLine();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (iniFile != null)
iniFile.Close();
}
}
else
throw new FileNotFoundException("Unable to locate " + iniPath);
}
/// <summary>
/// 返回给定section的值,key对。
/// </summary>
/// <param name="sectionName">Section name</param>
/// <param name="settingName">Key name</param>
public String GetSetting(String sectionName, String settingName)
{
SectionPair sectionPair;
sectionPair.Section = sectionName.ToUpper();
sectionPair.Key = settingName.ToUpper();
return (String)keyPairs[sectionPair];
}
/// <summary>
/// 列出给定的Section的所有行
/// </summary>
/// <param name="sectionName">Section to enum.</param>
public String[] EnumSection(String sectionName)
{
ArrayList tmpArray = new ArrayList();
foreach (SectionPair pair in keyPairs.Keys)
{
if (pair.Section == sectionName.ToUpper())
tmpArray.Add(pair.Key);
}
return (String[])tmpArray.ToArray(typeof(String));
}
/// <summary>
/// 向要保存的表添加或替换设置。
/// </summary>
/// <param name="sectionName">Section to add under.</param>
/// <param name="settingName">Key name to add.</param>
/// <param name="settingValue">Value of key.</param>
public void AddSetting(String sectionName, String settingName, String settingValue)
{
SectionPair sectionPair;
sectionPair.Section = sectionName.ToUpper();
sectionPair.Key = settingName.ToUpper();
if (keyPairs.ContainsKey(sectionPair))
keyPairs.Remove(sectionPair);
keyPairs.Add(sectionPair, settingValue);
}
/// <summary>
/// 用空值添加或替换要保存的表的设置。
/// </summary>
/// <param name="sectionName">Section</param>
/// <param name="settingName">Key</param>
public void AddSetting(String sectionName, String settingName)
{
AddSetting(sectionName, settingName, null);
}
/// <summary>
/// 删除设置
/// </summary>
/// <param name="sectionName">指定Section</param>
/// <param name="settingName">添加的Key</param>
public void DeleteSetting(String sectionName, String settingName)
{
SectionPair sectionPair;
sectionPair.Section = sectionName.ToUpper();
sectionPair.Key = settingName.ToUpper();
if (keyPairs.ContainsKey(sectionPair))
keyPairs.Remove(sectionPair);
}
/// <summary>
/// 保存设置到新文件。
/// </summary>
/// <param name="newFilePath">新的文件路径。</param>
public void SaveSettings(String newFilePath)
{
ArrayList sections = new ArrayList();
String tmpValue = "";
String strToSave = "";
foreach (SectionPair sectionPair in keyPairs.Keys)
{
if (!sections.Contains(sectionPair.Section))
sections.Add(sectionPair.Section);
}
foreach (String section in sections)
{
strToSave += ("[" + section + "]\r\n");
foreach (SectionPair sectionPair in keyPairs.Keys)
{
if (sectionPair.Section == section)
{
tmpValue = (String)keyPairs[sectionPair];
if (tmpValue != null)
tmpValue = "=" + tmpValue;
strToSave += (sectionPair.Key + tmpValue + "\r\n");
}
}
strToSave += "\r\n";
}
try
{
TextWriter tw = new StreamWriter(newFilePath);
tw.Write(strToSave);
tw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 将设置保存回ini文件。
/// </summary>
public void SaveSettings()
{
SaveSettings(iniFilePath);
}
}
调用方法:
niParser parser = new IniParser(@"C:\Settings.ini");
String newMessage;
newMessage = parser.GetSetting("MyWeb", "SiteName");
newMessage += parser.GetSetting("MyWeb", "Url");
newMessage += parser.GetSetting("MyINI", "Remark");