Skip to content

Instantly share code, notes, and snippets.

@cmpunches
Created October 15, 2015 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmpunches/2dfb342bf4cbd7c1defb to your computer and use it in GitHub Desktop.
Save cmpunches/2dfb342bf4cbd7c1defb to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace cli_20150929
{
class INI
{
string filePath;
string EXE = Assembly.GetExecutingAssembly().GetName().Name;
[DllImport("kernel32")]
static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
[DllImport("kernel32")]
static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);
public INI(string IniPath = null)
{
filePath = new FileInfo(IniPath ?? EXE + ".ini").FullName.ToString();
}
public string Read(string Key, string Section = null)
{
if (KeyExists(Key, Section))
{
var RetVal = new StringBuilder(255);
GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, filePath);
return RetVal.ToString();
} else {
Console.WriteLine("[{0}][{1}] is not configured in your settings.ini", Key, Section);
Console.ReadLine();
System.Environment.Exit(1);
return null;
}
}
public void Write(string Key, string Value, string Section = null)
{
WritePrivateProfileString(Section ?? EXE, Key, Value, filePath);
}
public void DeleteKey(string Key, string Section = null)
{
Write(Key, null, Section ?? EXE);
}
public void DeleteSection(string Section = null)
{
Write(null, null, Section ?? EXE);
}
public bool KeyExists(string Key, string Section = null)
{
return Read(Key, Section).Length > 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment