C# code get all keys from ini file

iniFileinfo.IniHelp ihelp = new iniFileinfo.IniHelp();

string iniFile="c://my.ini";
List<string> categories = ihelp.GetCategories(iniFile);
List<string> keys = ihelp.GetKeys(iniFile, "serverpath");
foreach (string key in keys)
{
// here in key variable you can key value
console.writeline(key);
}

Out put :-
files
operator

File my.ini

[serverpath]
files=solaris9
operator=mmas

[localpath]


iniFileinfo.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace iniFileinfo
{
using System;
using System.Runtime.InteropServices;
using System.Text;
class IniHelp
{
[DllImport("KERNEL32.DLL", EntryPoint = "GetPrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault,
string lpReturnString,
int nSize,
string lpFilename);
[DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFilename);
public List<string> GetCategories(string iniFile)
{
string returnString = new string(' ', 65536);
GetPrivateProfileString(null, null, null, returnString, 65536, iniFile);
char[] sep = {'\0'};
List<string> result = new List<string>(returnString.Split(sep));
result.RemoveRange(result.Count - 2, 2);
return result;
}
public List<string> GetKeys(string iniFile, string category)
{
string returnString = new string(' ', 32768);
GetPrivateProfileString(category, null, null, returnString, 32768, iniFile);
char[] sep = { '\0' };
List<string> result = new List<string>(returnString.Split(sep));
result.RemoveRange(result.Count - 2, 2);
return result;
}
public string GetIniFileString(string iniFile, string category, string key, string defaultValue)
{
string returnString = new string(' ', 1024);
GetPrivateProfileString(category, key, defaultValue, returnString, 1024, iniFile);
char[] sep = { '\0' };
return returnString.Split(sep)[0];
}
}
}

No comments:

Post a Comment