INI files are often used to save various settings or localized text, presumably in the following format:
[Section]key=value
However. NET Framework does not seem to provide a useful tool to manipulate it, perhaps because Ms wants us to use the config file of the settings class control?
But for a variety of reasons, I still do not like to use the settings class and this XML format config file.
Fortunately, there are two win32api that can help us complete the INI file control:
WritePrivateProfileString
GetPrivateProfileString
But it is very embarrassing that these two can be written in Chinese, the other is not good at Chinese ...
So I had to do it by myself, and I had to remember it in case I needed it later:
1 Abstract classConfigurationbase2 {3 Public Abstract stringPath {Get; }4 5 Public Abstract stringSection {Get; }6 7 /// <summary>8 ///Specify a good encoding format to support a variety of language text9 /// </summary>Ten Private ReadOnlyEncoding Encoding =Encoding.UTF8; One A Public voidClear () - { - File.delete (Path); the } - - Public voidSave () - { + file.writealllines (Path, lines. ToArray (), encoding); - } + A Private ReadOnlylist<string>lines; at - protectedconfigurationbase () - { - if(File.exists (Path)) - { -Lines =Newlist<string>( in File.ReadAllLines (Path, encoding)); - } to Else + { -Lines =Newlist<string>(); the } * } $ Panax Notoginseng protected stringGet (stringKeystringdefaultval) - { the if(lines. Count! =0) + { A stringSectionline = String.Format ("[{0}]", section); the stringKeyLine = String.Format ("{0}=", key); +Regex othersection =NewRegex (@"^\[[^\]+]\]$", regexoptions.compiled); - $ BOOLInsection =false; $ foreach(stringLineinchlines) - { - if(Sectionline = =Line ) the { -Insection =true;Wuyi } the Else if(Othersection.ismatch (line)) - { Wu if(insection) Break; - } About Else if(Insection &&Line . StartsWith (keyLine)) $ { - returnLine . Substring (keyline.length); - } - } A } + returnDefaultval; the } - $ protected voidSet (stringKeystringvalue) the { the stringSectionline = String.Format ("[{0}]", section); the stringKeyLine = String.Format ("{0}=", key); theRegex othersection =NewRegex (@"^\[[^\]+]\]$", regexoptions.compiled); - stringValueline = String.Format ("{0}{1}", keyLine, value); in the BOOLInsection =false; the for(inti =0; I < lines. Count; i++) About { the if(Sectionline = =Lines[i]) the { theInsection =true; + } - Else if(Othersection.ismatch (Lines[i])) the {Bayi if(insection) the { the lines. Insert (i, valueline); - Break; - } the } the Else if(Insection &&Lines[i]. StartsWith (keyLine)) the { theLines[i] =Valueline; - } the } the if(insection) the {94 lines. ADD (valueline); the } the Else the {98 lines. ADD (sectionline); About lines. ADD (valueline); - }101 }102}
[C #] INI file control class