using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApplication1
{
public class UIHelper
{
/// <summary>
/// 读写INI文件的类。
/// </summary>
// 读写INI文件相关。
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Ansi)]
public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Ansi)]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Ansi)]
public static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath);
[DllImport("KERNEL32.DLL ", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Ansi)]
public static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath);
/// <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(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, path);
return temp.ToString();
}
/// <summary>
/// 读取一个ini里面所有的节
/// </summary>
/// <param name="sections"></param>
/// <param name="path"></param>
/// <returns></returns>
public static int GetAllSectionNames(out string[] sections, string path)
{
int MAX_BUFFER = 32767;
IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
if (bytesReturned == 0)
{
sections = null;
return -1;
}
string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
Marshal.FreeCoTaskMem(pReturnedString);
//use of Substring below removes terminating null for split
sections = local.Substring(0, local.Length - 1).Split('