通过上一篇博客《C# 之 管理配置文件(一)》给大家介绍了一下对我们传统的app.config或者web.config配置文件中配置变量的读取和写入,今天来给大家介绍一下对ini文件中配置变量的读取和写入。
首先我们创建一个Test.ini的文件,其内容为:
[DateTime]
Value=2015/10/21 17:06:38
编写读取和写入方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
public static class IniHelper
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// 读取ini文件中节点的值
/// </summary>
/// <param name="Section">节</param>
/// <param name="Key">键</param>
/// <param name="FilePath">文件路径</param>
/// <returns></returns>
public static string IniReadValue(string Section, string Key, string FilePath)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, FilePath);
return temp.ToString();
}
/// <summary>
/// 往ini文件中节点写入值
/// </summary>
/// <param name="Section">节</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
/// <param name="filePath">文件路径</param>
public static void IniWriteValue(string Section, string Key, string Value, string filePath)
{
WritePrivateProfileString(Section, Key, Value, filePath);
}
}
}
调用我们的读取和写入方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string strFilePath = "C:/Users/焱/Desktop/ConsoleApplication2/ConsoleApplication2/Test.ini";
Console.WriteLine(IniHelper.IniReadValue("DateTime", "Value", strFilePath));
IniHelper.IniWriteValue("DateTime", "Value", DateTime.Now.ToString(), strFilePath);
Console.WriteLine(IniHelper.IniReadValue("DateTime", "Value", strFilePath));
}
}
}