Files
2023-03-28 17:02:05 +02:00

113 lines
3.8 KiB
C#

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;
/// <summary>
/// Constructor
/// </summary>
/// <PARAM name="INIPath"></PARAM>
public IniFile(string INIPath)
{
FileName = INIPath;
}
/// <summary>
/// Read data from the Ini file
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <returns></returns>
public string ReadString(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, FileName);
return temp.ToString();
}
/// <summary>
/// Read a string. If not found use default value
/// </summary>
/// <param name="Section"></param>
/// <param name="Key"></param>
/// <param name="DefaultVal"></param>
/// <returns></returns>
public string ReadString(string Section, string Key, string DefaultVal)
{
string temp = ReadString(Section, Key);
if (temp == "") temp = DefaultVal;
return temp;
}
/// <summary>
/// GetPrivateProfileString: import windows dll functions
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="def"></param>
/// <param name="retVal"></param>
/// <param name="size"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// GetPrivateProfileSection: import windows dll functions
/// </summary>
/// <param name="section"></param>
/// <param name="retVal"></param>
/// <param name="size"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileSection(string section, IntPtr retVal, uint size, string filePath);
/// <summary>
/// Read a complete section (keys=values)
/// </summary>
/// <param name="Section"></param>
/// Section name
/// <returns>
/// restituisce delle stringhe keys=values da suddividere appunto come key/val successivamente
/// </returns>
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');
}
}
}