Skip to content

Instantly share code, notes, and snippets.

@cmpunches
Created October 15, 2015 05:23
Show Gist options
  • Select an option

  • Save cmpunches/2dfb342bf4cbd7c1defb to your computer and use it in GitHub Desktop.

Select an option

Save cmpunches/2dfb342bf4cbd7c1defb to your computer and use it in GitHub Desktop.

Revisions

  1. Chris Punches created this gist Oct 15, 2015.
    63 changes: 63 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    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;
    }
    }
    }