1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; // Change this to match your program's normal namespace namespace MyProg { class IniFile // revision 11 { string Path; string EXE = Assembly.GetExecutingAssembly().GetName().Name; [DllImport( "kernel32" , CharSet = CharSet.Unicode)] static extern long WritePrivateProfileString( string Section, string Key, string Value, string FilePath); [DllImport( "kernel32" , CharSet = CharSet.Unicode)] 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 ) { return Read(Key, Section).Length > 0; } } } |
1 2 3 4 5 6 7 8 9 |
// Creates or loads an INI file in the same directory as your executable // named EXE.ini (where EXE is the name of your executable) var MyIni = new IniFile(); // Or specify a specific name in the current dir var MyIni = new IniFile( "Settings.ini" ); // Or specify a specific name in a specific dir var MyIni = new IniFile( @"C:\Settings.ini" ); |
1 2 |
MyIni.Write("DefaultVolume", "100"); MyIni.Write("HomePage", "http://www.google.com"); |
1 2 3 |
1 2 |
var DefaultVolume = MyIni.Read("DefaultVolume"); var HomePage = MyIni.Read("HomePage"); |
1 2 |
MyIni.Write("DefaultVolume", "100", "Audio"); MyIni.Write("HomePage", "http://www.google.com", "Web"); |
1 2 3 4 5 |
1 2 3 4 |
if(!MyIni.KeyExists("DefaultVolume", "Audio")) { MyIni.Write("DefaultVolume", "100", "Audio"); } |
1 |
MyIni.DeleteKey("DefaultVolume", "Audio"); |
1 |
MyIni.DeleteSection("Web"); |