Last active
March 25, 2023 18:42
-
-
Save heiswayi/56f4707a6cf45161807989db24dc3cea to your computer and use it in GitHub Desktop.
C# utilities - .INI file helper class
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; | |
namespace Utilities | |
{ | |
public class IniFile | |
{ | |
private string Path; | |
private 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.ToString(); | |
} | |
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) | |
{ | |
return Read(Key, Section).Length > 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment