Last active
February 13, 2017 12:37
-
-
Save mirhec/0aba02f35abbd121fca8c4a560b803fb to your computer and use it in GitHub Desktop.
IniFile implementation based on the original Windows P/Invoke, grabbed from http://stackoverflow.com/a/14906422/4112816
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Reflection; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
internal class IniFile // revision 11 | |
{ | |
readonly string _path; | |
readonly string _exe = Assembly.GetExecutingAssembly().GetName().Name; | |
[DllImport("kernel32", CharSet = CharSet.Unicode)] | |
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath); | |
[DllImport("kernel32", CharSet = CharSet.Unicode)] | |
private static extern int GetPrivateProfileString(string section, string key, string Default, StringBuilder retVal, int size, string filePath); | |
public IniFile(string iniPath = null) | |
{ | |
_path = new FileInfo(iniPath ?? _exe + ".ini").FullName; | |
} | |
public string Read(string key, string section = null) | |
{ | |
var retVal = new StringBuilder(255); | |
GetPrivateProfileString(section ?? _exe, key, "", retVal, 255, _path); | |
return retVal.ToString(); | |
} | |
public void Write(string key, string value, string section = null) => WritePrivateProfileString(section ?? _exe, key, value, _path); | |
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) => Read(key, section).Length > 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment