C# 操作Ini文件文章来源地址https://www.toymoban.com/news/detail-590033.html
public class IniHelper
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def,StringBuilder retVal, int size, string filePath);
string path;
public IniHelper(string path)
{
this.path = path;
}
/// <summary>
/// 读取INI文件中所有节点名称(Section)
/// </summary>
/// <returns></returns>
public string[] GetAllSections()
{
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, path);
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>
/// 读取指定Section下所有Key名称
/// </summary>
/// <param name="iniFile"></param>
/// <param name="section"></param>
/// <returns></returns>
public string[] GetAllKeys(string section)
{
const int SIZE = 1024 * 10; //默认为32767
string[] value = new string[0];
char[] chars = new char[SIZE]; //返回值
uint bytesReturned = GetPrivateProfileString(section, null, null, chars, SIZE, path);
if (bytesReturned != 0)
{
value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
chars = null;
return value;
}
/// <summary>
/// Ini读取
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public void Write(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, path);
}
/// <summary>
/// Ini写入
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns></returns>
public string Read(string section, string key)
{
StringBuilder temp = new StringBuilder(255);
GetPrivateProfileString(section, key, "", temp, 255, path);
return temp.ToString();
}
}
文章来源:https://www.toymoban.com/news/detail-590033.html
到了这里,关于C# 操作Ini文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!