Original: How C # reads and creates INI files
In the process of doing the project, sometimes you need to save some simple configuration information, you can use XML, you can also use the INI file. Here's how to read INI in C #, and I believe most of my friends have used it this way.
INI file is stored in the following way,
[Section]key=valuekey=value
Read Write method,
[DllImport ("kernel32")] private static extern long WritePrivateProfileString (string section, string key, St Ring val, string filePath); [DllImport ("kernel32")] private static extern int getprivateprofilestring (string lpappname, String lpkeyname, Strin G Lpdefault, StringBuilder lpreturnedstring, int nSize, string lpfilename); [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] private static extern uint Getprivateprofilesection (string LPAP PName, IntPtr lpreturnedstring, uint nSize, string lpfilename); private static string ReadString (string section, String key, String Def, string filePath) {Stringbuilde R temp = new StringBuilder (1024); try {getprivateprofilestring (section, key, Def, temp, 1024x768, filePath); } catch {} return temp. ToString (); }///<summary>////For all keys///</summary>///<param name= "section" ></param>//<param name= "FilePath" ></param>//<returns ></returns> public static string[] Readiniallkeys (string section,string filePath) {UInt Max_buffer = 32767; string[] items = new String[0]; IntPtr preturnedstring = Marshal.alloccotaskmem ((int) max_buffer * sizeof (char)); UInt32 bytesreturned = getprivateprofilesection (section, preturnedstring, Max_buffer, FilePath); if (! ( bytesreturned = = max_buffer-2) | | (bytesreturned = = 0)) {String returnedstring = Marshal.ptrtostringauto (preturnedstring, (int) bytesreturned); Items = Returnedstring.split (new char[] {' n '}, stringsplitoptions.removeemptyentries); } marshal.freecotaskmem (preturnedstring); return items; }///<summary>///Based on Section,key///</summary>//<param name= "section" ></param>//<param name= "keys" ></param>//<param name= "f Ilepath ">ini file path </param>///<returns></returns> public static string Readinikeys (Strin G section, string keys, String filePath) {return ReadString (section, Keys, "", FilePath); }//<summary>//Save INI//</summary>//<param name= "section" ></para m>//<param name= "key" ></param>///<param Name= "value" ></param>//< ;p Aram Name= "filePath" >ini file path </param> public static void Writeinikeys (string section, string key, String Value, String filePath) {writeprivateprofilestring (section, key, value, FilePath); }
If you want to delete an item:
Writeinikeys (section, key, NULL, Recordinipath);
If the above can read and write, then how to create the INI file?
[DllImport ("kernel32")]public static extern long WritePrivateProfileString (string section, string key, String value, String iniPath);
Call this method to create your INI file and the values you want to save.
Of course, the above INI operation is not very detailed, the following from the HTTP://BLOG.CSDN.NET/SDFKFKD/ARTICLE/DETAILS/7050733 blog reproduced a description of the INI operation, more detailed, worth learning.
public class Inioperationclass {#region INI file operation/* * API action method for INI file, where nodes (section), key (keys) are not Case-sensitive * If the specified INI file does not exist, the file is created automatically. * * CharSet defines what type to use when using the relevant method must use the corresponding type * For example Getprivateprofilesectionnames declared as CharSet.Auto, then you should use Marshal.ptrtostringauto to read the relevant content * If you are using CharSet.Ansi, you should use Marshal.ptrtostringansi to read the content * */#region API declaration///<summary>//Get All node names (section)///</summary>/// Lt;param name= "Lpszreturnbuffer" > Memory address where node name is stored, each node is separated by \//<param name= "nSize" > Memory size (Chara Cters) </param>//<param name= "lpfilename" >ini file </param>//<returns> actual length of content, 0 means no There is content for nSize-2 that indicates insufficient memory size </returns> [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] private static Exte RN UINT Getprivateprofilesectionnames (IntPtr lpszreturnbuffer, uint nSize, string lpfilename); <summary>///Get all keys and value in a specified node (section)///</summary>//<param name= "LpA Ppname "> Node name </param>//<param name=" lpreturnedstring "> Memory address of the return value, separated by \//For each </param>// <param name= "NSize" > Memory size (characters) </param>//<param name= "lpfilename" >ini file </param> <returns> the actual length of the content, 0 means no content, for nSize-2 indicates insufficient memory size </returns> [DllImport ("kernel32.dll", CharSet = CharS Et. Auto)] private static extern uint Getprivateprofilesection (string lpappname, IntPtr lpreturnedstring, uint nSize, S Tring lpFileName); <summary>///Read the value of the key specified in the INI file///</summary>//<param name= "Lpappname" > Node name. If NULL, all node names in the INI are read and each node name is separated by </param>//<param name= "Lpkeyname" >key name. If NULL, all keys in the specified node in the INI are read, each key is separated by \ </param>//<param name= "Lpdefault" > The default value when read fails </param> <param NAMe= "Lpreturnedstring" > read the content buffer, after reading, the extra place uses the \ Fill </param>//<param name= "NSize" > The length of the content buffer </param >//<param name= "lpfilename" >ini filename </param>//<returns> actual read length </returns> [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] private static extern uint GetPrivateProfileString (string l Pappname, String lpkeyname, String Lpdefault, [in, out] char[] lpreturnedstring, uint nSize, string lpfilename); Another way of declaring this is that using StringBuilder as a buffer type has the disadvantage of not being able to accept the \ n characters, truncating the//and subsequent characters,//So it is not applicable for lpappname or lpkeyname null [Dllimpor T ("kernel32.dll", CharSet = CharSet.Auto)] private static extern uint GetPrivateProfileString (string lpappname, str ing lpkeyname, string lpdefault, StringBuilder lpreturnedstring, uint nSize, string lpfilename); Another declaration, using string as the buffer type with char[] [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] private static extern UI NT GetPrivateProfileString (string lpappname, STring Lpkeyname, String lpdefault, String lpreturnedstring, uint nSize, string lpfilename); <summary>///writes the specified key-value pair to the specified node and replaces it if it already exists. </summary>//<param name= "Lpappname" > node, if this node is not present, create this node </param>///<param name= " Lpstring ">item key-value pairs, multiple with a, shaped like key1=value1\0key2=value2//<para> if string. Empty, delete all content under the specified node, retain node </para>///<para> if NULL, delete all content under the specified node, and delete the node </para>//</pa ram>//<param name= "lpfilename" >ini file </param>///<returns> Successful write </returns> [DllImport ("kernel32.dll", CharSet = CharSet.Auto)] [Return:marshalas (Unmanagedtype.bool)]//Can not have this line private static extern Bool Writeprivateprofilesection (string l Pappname, String lpstring, string lpfilename); <summary>////writes the specified key and value to the specified node and replaces if it already exists///</summary>//<param name= "Lpappname" & gt; node name </param> <param name= "Lpkeyname" > Key name. If NULL, deletes the specified node and all of its items </param>//<param name= "lpstring" > Value content. If NULL, the key specified in the specified node is deleted. </param>//<param name= "lpfilename" >ini file </param>//<returns> operation succeeded </returns& Gt [DllImport ("kernel32.dll", CharSet = CharSet.Auto, SetLastError = True)] [Return:marshalas (Unmanagedtype.bool)] private static extern Bool WritePrivateProfileString (string lpappname, Stri Ng Lpkeyname, String lpstring, string lpfilename); #endregion #region Package///<summary>//Read all node names in the INI file specified in the INI file (section)///</summar y>//<param name= "iniFile" >ini file </param>///<returns> all nodes, no content returned String[0]</return s> public static string[] Inigetallsectionnames (string iniFile) {uint Max_buffer = 32767; Default is 32767 string[] sections = new string[0]; return value//Request memory IntPtr preturnedstring = Marshal.alloccotaskmem ((int) max_buffer * sizeof (char)); UINT bytesreturned = Inioperationclass.getprivateprofilesectionnames (preturnedstring, MAX_BUFFER, iniFile); if (bytesreturned! = 0) {//reads the contents of the specified memory string local = Marshal.ptrtostringauto (pRet urnedstring, (int) bytesreturned). ToString (); Each node is separated by a, and at the end there is a sections = local. Split (new char[] {' n '}, stringsplitoptions.removeemptyentries); }//Free memory Marshal.freecotaskmem (preturnedstring); return sections; }///<summary>//Get all entries in the specified node (section) in the INI file (key=value form)///</summary>//&L T;param name= "iniFile" >ini file </param>//<param name= "section" > Node name </param>//<ret Urns> all items in the specified node, no content returned string[0]</returns> public static string[] Inigetallitems (String iniFile, String section) {//return value in the form of key=value, for example color=red uint max_buffer = 32767; Default is 32767 string[] items = new String[0]; return value//Allocate memory IntPtr preturnedstring = Marshal.alloccotaskmem ((int) max_buffer * sizeof (char)); UINT bytesreturned = inioperationclass.getprivateprofilesection (section, preturnedstring, Max_buffer, iniFile); if (! ( bytesreturned = = max_buffer-2) | | (bytesreturned = = 0)) {String returnedstring = Marshal.ptrtostringauto (preturnedstring, (int) bytesreturned); Items = Returnedstring.split (new char[] {' n '}, stringsplitoptions.removeemptyentries); } marshal.freecotaskmem (preturnedstring); Free memory return items; }///<summary>//Get a key list of all entries in the specified node (section) in the INI file///</summary>//<param Name= "IniFile" >ini file </param>///<param name= "section" > NodeName </param>///<returns> if no content, back string[0]</returns> public static string[] Inigetallitemk Eys (string iniFile, string section) {string[] value = new String[0]; const int SIZE = 1024 * 10; if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } char[] chars = new Char[size]; UINT bytesreturned = inioperationclass.getprivateprofilestring (section, NULL, NULL, chars, SIZE, iniFile); if (bytesreturned! = 0) {value = new string (chars). Split (new char[] {' n '}, stringsplitoptions.removeemptyentries); } chars = null; return value; }///<summary>//Read the string value of key specified in INI file///</summary>//<param name= "IniFile ">ini file </param>//<param name=" section "> Node name </param>//<paramName= "key" > Key name </param>//<param name= "DefaultValue" > If no default value for this key is used </param>//<re Turns> Read value </returns> public static string Inigetstringvalue (string iniFile, string section, string key, S Tring defaultvalue) {string value = DefaultValue; const int SIZE = 1024 * 10; if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } if (string. IsNullOrEmpty (key)) {throw new ArgumentException ("must specify Key name (key)", "key"); } StringBuilder sb = new StringBuilder (SIZE); UINT bytesreturned = inioperationclass.getprivateprofilestring (section, Key, DefaultValue, SB, SIZE, iniFile); if (bytesreturned! = 0) {value = sb. ToString (); } SB = null; return value; }//<summary>//in INIFile, the specified key-value pair is written to the specified node, and if it already exists replace//</summary>//<param name= "iniFile" >ini file </param> <param name= "section" > node, if this node does not exist, this node is created </param>//<param name= "items" > key-value pairs, multiple separated by a, shaped like key1= value1\0key2=value2</param>//<returns></returns> public static bool Iniwriteitems (Strin g IniFile, string section, string items) {if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } if (string. IsNullOrEmpty (items)) {throw new ArgumentException ("key value pair must be specified", "items"); } return inioperationclass.writeprivateprofilesection (section, items, iniFile); }///<summary>///In the INI file, specify that the node writes the specified key and value. If it already exists, replace it. If not, create it. </summary>//<param name= "iniFile" >ini file </param>//<param name= "section" > Node & lt;/param>//<param name= "key" > Keys </param>///<param Name= "value" > Value </param>// /<returns> Whether the operation was successful </returns> public static bool Iniwritevalue (string iniFile, string section, string key , string value) {if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } if (string. IsNullOrEmpty (key)) {throw new ArgumentException ("must specify Key name", "Key"); } if (value = = null) {throw new ArgumentException ("value cannot be null", "values"); } return inioperationclass.writeprivateprofilestring (section, key, value, IniFile); }///<summary>///In the INI file, delete the specified key in the specified node. </summary>//<param name= "iniFile" >ini file </param>//<param name= "section" > Node & lt;/param>//<param name= "key" > Keys</param>///<returns> successful operation </returns> public static bool Inideletekey (string iniFile, str ing section, string key) {if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } if (string. IsNullOrEmpty (key)) {throw new ArgumentException ("must specify Key name", "Key"); } return inioperationclass.writeprivateprofilestring (section, key, NULL, iniFile); }///<summary>///In the INI file, delete the specified node. </summary>//<param name= "iniFile" >ini file </param>//<param name= "section" > Node & Lt;/param>//<returns> Whether the operation was successful </returns> public static bool Inideletesection (String iniFile, String section) {if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } return inioperationclass.writeprivateprofilestring (section, NULL, NULL, iniFile); }///<summary>///In the INI file, delete all content from the specified node. </summary>//<param name= "iniFile" >ini file </param>//<param name= "section" > Node & Lt;/param>//<returns> Whether the operation was successful </returns> public static bool Iniemptysection (string iniFile, S Tring section) {if (string. IsNullOrEmpty (section)) {throw new ArgumentException ("must specify node name", "section"); } return Inioperationclass.writeprivateprofilesection (section, String. Empty, IniFile); } private void Testiniinioperation () {String file = "F:\\testini.ini"; Write/Update key value Iniwritevalue (file, "Desktop", "Color", "Red"); Iniwritevalue (file, "Desktop", "Width", "3270"); Iniwritevalue (file, "Toolbar", "Items", "Save,delete,open"); IniwrItevalue (file, "Toolbar", "Dock", "True"); Write a batch of key values Iniwriteitems (file, "menu", "file= file \0view= view \0edit= edit"); Get all the nodes in the file string[] sections = inigetallsectionnames (file); Gets all the items in the specified node string[] items = inigetallitems (file, "menu"); Gets all keys in the specified node string[] keys = Inigetallitemkeys (file, "menu"); Gets the value of the specified key string value = Inigetstringvalue (file, "Desktop", "color", null); Deletes the specified key Inideletekey (file, "desktop", "color"); Deletes the specified node inideletesection (file, "desktop"); Empties the specified node iniemptysection (file, "toolbar"); } #endregion #endregion}
How C # Reads and creates INI files