using System.IO; using System.Runtime.InteropServices; using System.Text; namespace ini { class iniFile { #region dll imports [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); #endregion /// /// The path to the ini file /// public string path; /// /// INIFile Constructor. /// If the file doesn't exists, it will be created /// /// /// Path of the ini file public iniFile(string inipath) { path = inipath; } /// /// INIFile Constructor. /// Be sure to add the path /// public iniFile() { } /// /// Read Data from the INI File /// /// section name /// Section name /// key value /// Key Name /// returns the value for the specified key as a string public string GetValue(string section, string key) { StringBuilder temp = new StringBuilder(' ', 1024); int i = GetPrivateProfileString(section, key, null, temp, 1024, path); return temp.ToString(); } /// /// Read Data from the INI File /// /// section name /// Section name /// key value /// Key Name /// returns the value for the specified key as a string public string GetValue(string section, string key, string iniPath) { StringBuilder temp = new StringBuilder(' ', 1024); int i = GetPrivateProfileString(section, key, null, temp, 1024, iniPath); return temp.ToString(); } /// /// Write Data to the INI File /// /// /// Section name /// /// Key Name /// /// Value Name /// /// /// Value Name public void WriteValue(string section, string key, string value) { WritePrivateProfileString(section, key, value, path); } /// /// Write Data to the INI File /// /// /// Section name /// /// Key Name /// /// Value Name /// /// /// Value Name public void WriteValue(string section, string key, string value, string iniPath) { WritePrivateProfileString(section, key, value, iniPath); } /// /// Check to find if the section exists in the current ini file /// /// public bool isSectionExsists(string section) { if (File.Exists(path)) { StreamReader sr = new StreamReader(path); while (!sr.EndOfStream) { if (sr.ReadLine() == "[" + section + "]") { sr.Close(); sr.Dispose(); return true; } } sr.Close(); sr.Dispose(); return false; } else throw new FileNotFoundException(); } /// /// Check to find if the section exists in the current ini file /// /// /// /// public bool isSectionExsists(string section, string iniPath) { if (File.Exists(iniPath)) { StreamReader sr = new StreamReader(iniPath); while (!sr.EndOfStream) { if (sr.ReadLine() == "[" + section + "]") { sr.Close(); sr.Dispose(); return true; } } sr.Close(); sr.Dispose(); return false; } else throw new FileNotFoundException(); } /* /// /// Check to find if the key exists in the specified section. /// BROKEN! /// /// /// public bool isKeyExsists(string section, string key) { return false; }*/ } }