C#中读取ini配置文件 [DllImport("kernel32.dll")]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
/// <summary>
/// 保存配置文件
/// </summary>
/// <param name="strAppName">配置节点名称</param>
/// <param name="strKeyName">配置名</param>
/// <param name="strString">配置值</param>
/// <param
name="strFileName">配置文件名</param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool WritePrivateProfileString(string strAppName,
string strKeyName,
string strDefault,
string strFileName);
/// <summary>
/// 读取配置文件值
/// </summary>
/// <param name="strAppName">配置节点名称</param>
/// <param name="strKeyName">配置名</param>
/// <param name="strDefault">返回的默认值</param>
/// <param name="sbReturnString">返回StringBuilder Cache对象</param>
/// <param name="nSize">缓冲区大小</param>
/// <param name="strFileName">配置文件名</param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool GetPrivateProfileString(string strAppName,
string strKeyName,
string strDefault,
StringBuilder sbReturnString,
int nSize,
string strFileName);
/// <summary>
/// 读取配置文件中的指定配置节点,并返回整型值
/// </summary>
/// <param name="strAppName">配置节点名称</param>
/// <param name="strKeyName">配置名</param>
/// <param name="nDefault">返回的默认值</param>
/// <param name="strFileName">配置文件名</param>
/// <returns></returns>
[DllImport("Kernel32.dll")]
public static extern int GetPrivateProfileInt(string strAppName,
string strKeyName,
int nDefault,
string strFileName);
static void Main(string[] args)
{
string strAppPath = "";
string[] stringList = {"1234","b","c","d"};
foreach(string str in stringList)
{
Console.WriteLine(str);
}
WritePrivateProfileString("Settings", "Url", "http://dayrl.cnblogs.com%22,%22c//config.ini");
WritePrivateProfileString("Settings", "Time", "37","c:\config.ini");
StringBuilder sb = new StringBuilder(256);
GetPrivateProfileString("Settings", "Url", "http://", sb, 256,"c:\config.ini");
Console.WriteLine(sb);
GetPrivateProfileString("Settings", "Time", "10", sb, 256,"c:\config.ini");
Console.WriteLine(sb);
int nReturnFromProFile = GetPrivateProfileInt("Settings", "Time", 0, "c:\config.INI");
Console.WriteLine(nReturnFromProFile);
Console.ReadLine();
}
}
}