using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace WebDoorCreator.Core
{
public class IniFile
{
public string FileName;
///
/// Constructor
///
///
public IniFile(string INIPath)
{
FileName = INIPath;
}
///
/// Read data from the Ini file
///
///
///
///
public string ReadString(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, FileName);
return temp.ToString();
}
///
/// Read a string. If not found use default value
///
///
///
///
///
public string ReadString(string Section, string Key, string DefaultVal)
{
string temp = ReadString(Section, Key);
if (temp == "") temp = DefaultVal;
return temp;
}
///
/// GetPrivateProfileString: import windows dll functions
///
///
///
///
///
///
///
///
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
///
/// GetPrivateProfileSection: import windows dll functions
///
///
///
///
///
///
[DllImport("kernel32")]
private static extern int GetPrivateProfileSection(string section, IntPtr retVal, uint size, string filePath);
///
/// Read a complete section (keys=values)
///
///
/// Section name
///
/// restituisce delle stringhe keys=values da suddividere appunto come key/val successivamente
///
public string[] ReadSection(string Section)
{
const int bufferSize = 2048; // max is 32767
StringBuilder returnedString = new StringBuilder();
IntPtr pReturnedString = Marshal.AllocCoTaskMem(bufferSize);
try
{
int bytesReturned = GetPrivateProfileSection(Section, pReturnedString, bufferSize, FileName);
if (bytesReturned > 0)
{
//bytesReturned -1 to remove trailing \0
for (int i = 0; i < bytesReturned - 1; i++)
{
var currPointer = IntPtr.Add(pReturnedString, i);
var currChar = (char)Marshal.ReadByte(currPointer);
returnedString.Append(currChar);
}
}
}
finally
{
Marshal.FreeCoTaskMem(pReturnedString);
}
string sectionData = returnedString.ToString();
return sectionData.Split('\0');
}
}
}