C#如何讀寫和創建INI文件


在做項目過程中,有時需要保存一些簡單的配置信息,可以使用xml,也可以使用INI文件。下面是C#中讀取INI的方法,相信大部分朋友都使用過這種方式。
INI文件的存儲方式如下,

[csharp]  view plain  copy
 
 print?
  1. [section]  
  2. key=value  
  3. key=value  

讀取寫入方法,

[csharp]  view plain  copy
 
 print?
  1. [DllImport("kernel32")]  
  2. private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);  
  3.   
  4. [DllImport("kernel32")]  
  5. private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);  
  6.   
  7. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  8. private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);  
  9.   
  10. private static string ReadString(string section, string key, string def, string filePath)  
  11. {  
  12.     StringBuilder temp = new StringBuilder(1024);  
  13.   
  14.     try  
  15.     {  
  16.         GetPrivateProfileString(section, key, def, temp, 1024, filePath);  
  17.     }  
  18.     catch  
  19.     { }  
  20.     return temp.ToString();  
  21. }  
  22. /// <summary>  
  23. /// 根據section取所有key  
  24. /// </summary>  
  25. /// <param name="section"></param>  
  26. /// <param name="filePath"></param>  
  27. /// <returns></returns>  
  28. public static string[] ReadIniAllKeys(string section,string filePath)  
  29. {  
  30.     UInt32 MAX_BUFFER = 32767;    
  31.   
  32.     string[] items = new string[0];    
  33.   
  34.     IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));  
  35.   
  36.     UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath);  
  37.   
  38.     if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))  
  39.     {  
  40.         string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);  
  41.   
  42.         items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);  
  43.     }  
  44.   
  45.     Marshal.FreeCoTaskMem(pReturnedString);   
  46.   
  47.     return items;  
  48. }  
  49.   
  50. /// <summary>  
  51. /// 根據section,key取值  
  52. /// </summary>  
  53. /// <param name="section"></param>  
  54. /// <param name="keys"></param>  
  55. /// <param name="filePath">ini文件路徑</param>  
  56. /// <returns></returns>  
  57. public static string ReadIniKeys(string section, string keys, string filePath)  
  58. {  
  59.     return ReadString(section, keys, "", filePath);  
  60. }  
  61.   
  62. /// <summary>  
  63. /// 保存ini  
  64. /// </summary>  
  65. /// <param name="section"></param>  
  66. /// <param name="key"></param>  
  67. /// <param name="value"></param>  
  68. /// <param name="filePath">ini文件路徑</param>  
  69. public static void WriteIniKeys(string section, string key, string value, string filePath)  
  70. {  
  71.     WritePrivateProfileString(section, key, value, filePath);  
  72. }  

如果要刪除某一項:

[csharp]  view plain  copy
 
 print?
  1. WriteIniKeys(section, key, null, recordIniPath);  

如上就可以讀取和寫入了,那么INI文件如何創建呢?

[csharp]  view plain  copy
 
 print?
  1. [DllImport("kernel32")]  
  2. public static extern long WritePrivateProfileString(string section, string key, string value, string iniPath);  

調用該方法,即可創建你的ini文件和想要保存的值。

 

當然上面的ini操作並不是很詳細的,以下從http://blog.csdn.net/sdfkfkd/article/details/7050733的博客轉載的一片描述INI操作的,比較詳細,值得學習。

[csharp]  view plain  copy
 
 print?
  1. public class INIOperationClass  
  2. {  
  3.  
  4.     #region INI文件操作  
  5.   
  6.     /* 
  7.      * 針對INI文件的API操作方法,其中的節點(Section)、鍵(KEY)都不區分大小寫 
  8.      * 如果指定的INI文件不存在,會自動創建該文件。 
  9.      *  
  10.      * CharSet定義的時候使用了什么類型,在使用相關方法時必須要使用相應的類型 
  11.      *      例如 GetPrivateProfileSectionNames聲明為CharSet.Auto,那么就應該使用 Marshal.PtrToStringAuto來讀取相關內容 
  12.      *      如果使用的是CharSet.Ansi,就應該使用Marshal.PtrToStringAnsi來讀取內容 
  13.      *       
  14.      */  
  15.  
  16.     #region API聲明  
  17.   
  18.     /// <summary>  
  19.     /// 獲取所有節點名稱(Section)  
  20.     /// </summary>  
  21.     /// <param name="lpszReturnBuffer">存放節點名稱的內存地址,每個節點之間用\0分隔</param>  
  22.     /// <param name="nSize">內存大小(characters)</param>  
  23.     /// <param name="lpFileName">Ini文件</param>  
  24.     /// <returns>內容的實際長度,為0表示沒有內容,為nSize-2表示內存大小不夠</returns>  
  25.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  26.     private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);  
  27.   
  28.     /// <summary>  
  29.     /// 獲取某個指定節點(Section)中所有KEY和Value  
  30.     /// </summary>  
  31.     /// <param name="lpAppName">節點名稱</param>  
  32.     /// <param name="lpReturnedString">返回值的內存地址,每個之間用\0分隔</param>  
  33.     /// <param name="nSize">內存大小(characters)</param>  
  34.     /// <param name="lpFileName">Ini文件</param>  
  35.     /// <returns>內容的實際長度,為0表示沒有內容,為nSize-2表示內存大小不夠</returns>  
  36.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  37.     private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);  
  38.   
  39.     /// <summary>  
  40.     /// 讀取INI文件中指定的Key的值  
  41.     /// </summary>  
  42.     /// <param name="lpAppName">節點名稱。如果為null,則讀取INI中所有節點名稱,每個節點名稱之間用\0分隔</param>  
  43.     /// <param name="lpKeyName">Key名稱。如果為null,則讀取INI中指定節點中的所有KEY,每個KEY之間用\0分隔</param>  
  44.     /// <param name="lpDefault">讀取失敗時的默認值</param>  
  45.     /// <param name="lpReturnedString">讀取的內容緩沖區,讀取之后,多余的地方使用\0填充</param>  
  46.     /// <param name="nSize">內容緩沖區的長度</param>  
  47.     /// <param name="lpFileName">INI文件名</param>  
  48.     /// <returns>實際讀取到的長度</returns>  
  49.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  50.     private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);  
  51.   
  52.     //另一種聲明方式,使用 StringBuilder 作為緩沖區類型的缺點是不能接受\0字符,會將\0及其后的字符截斷,  
  53.     //所以對於lpAppName或lpKeyName為null的情況就不適用  
  54.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  55.     private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);  
  56.   
  57.     //再一種聲明,使用string作為緩沖區的類型同char[]  
  58.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  59.     private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName);  
  60.   
  61.     /// <summary>  
  62.     /// 將指定的鍵值對寫到指定的節點,如果已經存在則替換。  
  63.     /// </summary>  
  64.     /// <param name="lpAppName">節點,如果不存在此節點,則創建此節點</param>  
  65.     /// <param name="lpString">Item鍵值對,多個用\0分隔,形如key1=value1\0key2=value2  
  66.     /// <para>如果為string.Empty,則刪除指定節點下的所有內容,保留節點</para>  
  67.     /// <para>如果為null,則刪除指定節點下的所有內容,並且刪除該節點</para>  
  68.     /// </param>  
  69.     /// <param name="lpFileName">INI文件</param>  
  70.     /// <returns>是否成功寫入</returns>  
  71.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]  
  72.     [return: MarshalAs(UnmanagedType.Bool)]     //可以沒有此行  
  73.     private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);  
  74.   
  75.     /// <summary>  
  76.     /// 將指定的鍵和值寫到指定的節點,如果已經存在則替換  
  77.     /// </summary>  
  78.     /// <param name="lpAppName">節點名稱</param>  
  79.     /// <param name="lpKeyName">鍵名稱。如果為null,則刪除指定的節點及其所有的項目</param>  
  80.     /// <param name="lpString">值內容。如果為null,則刪除指定節點中指定的鍵。</param>  
  81.     /// <param name="lpFileName">INI文件</param>  
  82.     /// <returns>操作是否成功</returns>  
  83.     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]  
  84.     [return: MarshalAs(UnmanagedType.Bool)]  
  85.     private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);  
  86.  
  87.     #endregion  
  88.  
  89.     #region 封裝  
  90.   
  91.     /// <summary>  
  92.     /// 讀取INI文件中指定INI文件中的所有節點名稱(Section)  
  93.     /// </summary>  
  94.     /// <param name="iniFile">Ini文件</param>  
  95.     /// <returns>所有節點,沒有內容返回string[0]</returns>  
  96.     public static string[] INIGetAllSectionNames(string iniFile)  
  97.     {  
  98.         uint MAX_BUFFER = 32767;    //默認為32767  
  99.   
  100.         string[] sections = new string[0];      //返回值  
  101.   
  102.         //申請內存  
  103.         IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));  
  104.         uint bytesReturned = INIOperationClass.GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);  
  105.         if (bytesReturned != 0)  
  106.         {  
  107.             //讀取指定內存的內容  
  108.             string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();  
  109.   
  110.             //每個節點之間用\0分隔,末尾有一個\0  
  111.             sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);  
  112.         }  
  113.   
  114.         //釋放內存  
  115.         Marshal.FreeCoTaskMem(pReturnedString);  
  116.   
  117.         return sections;  
  118.     }  
  119.   
  120.     /// <summary>  
  121.     /// 獲取INI文件中指定節點(Section)中的所有條目(key=value形式)  
  122.     /// </summary>  
  123.     /// <param name="iniFile">Ini文件</param>  
  124.     /// <param name="section">節點名稱</param>  
  125.     /// <returns>指定節點中的所有項目,沒有內容返回string[0]</returns>  
  126.     public static string[] INIGetAllItems(string iniFile, string section)  
  127.     {  
  128.         //返回值形式為 key=value,例如 Color=Red  
  129.         uint MAX_BUFFER = 32767;    //默認為32767  
  130.   
  131.         string[] items = new string[0];      //返回值  
  132.   
  133.         //分配內存  
  134.         IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));  
  135.   
  136.         uint bytesReturned = INIOperationClass.GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile);  
  137.   
  138.         if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))  
  139.         {  
  140.   
  141.             string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);  
  142.             items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);  
  143.         }  
  144.   
  145.         Marshal.FreeCoTaskMem(pReturnedString);     //釋放內存  
  146.   
  147.         return items;  
  148.     }  
  149.   
  150.     /// <summary>  
  151.     /// 獲取INI文件中指定節點(Section)中的所有條目的Key列表  
  152.     /// </summary>  
  153.     /// <param name="iniFile">Ini文件</param>  
  154.     /// <param name="section">節點名稱</param>  
  155.     /// <returns>如果沒有內容,反回string[0]</returns>  
  156.     public static string[] INIGetAllItemKeys(string iniFile, string section)  
  157.     {  
  158.         string[] value = new string[0];  
  159.         const int SIZE = 1024 * 10;  
  160.   
  161.         if (string.IsNullOrEmpty(section))  
  162.         {  
  163.             throw new ArgumentException("必須指定節點名稱", "section");  
  164.         }  
  165.   
  166.         char[] chars = new char[SIZE];  
  167.         uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);  
  168.   
  169.         if (bytesReturned != 0)  
  170.         {  
  171.             value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);  
  172.         }  
  173.         chars = null;  
  174.   
  175.         return value;  
  176.     }  
  177.   
  178.     /// <summary>  
  179.     /// 讀取INI文件中指定KEY的字符串型值  
  180.     /// </summary>  
  181.     /// <param name="iniFile">Ini文件</param>  
  182.     /// <param name="section">節點名稱</param>  
  183.     /// <param name="key">鍵名稱</param>  
  184.     /// <param name="defaultValue">如果沒此KEY所使用的默認值</param>  
  185.     /// <returns>讀取到的值</returns>  
  186.     public static string INIGetStringValue(string iniFile, string section, string key, string defaultValue)  
  187.     {  
  188.         string value = defaultValue;  
  189.         const int SIZE = 1024 * 10;  
  190.   
  191.         if (string.IsNullOrEmpty(section))  
  192.         {  
  193.             throw new ArgumentException("必須指定節點名稱", "section");  
  194.         }  
  195.   
  196.         if (string.IsNullOrEmpty(key))  
  197.         {  
  198.             throw new ArgumentException("必須指定鍵名稱(key)", "key");  
  199.         }  
  200.   
  201.         StringBuilder sb = new StringBuilder(SIZE);  
  202.         uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile);  
  203.   
  204.         if (bytesReturned != 0)  
  205.         {  
  206.             value = sb.ToString();  
  207.         }  
  208.         sb = null;  
  209.   
  210.         return value;  
  211.     }  
  212.   
  213.     /// <summary>  
  214.     /// 在INI文件中,將指定的鍵值對寫到指定的節點,如果已經存在則替換  
  215.     /// </summary>  
  216.     /// <param name="iniFile">INI文件</param>  
  217.     /// <param name="section">節點,如果不存在此節點,則創建此節點</param>  
  218.     /// <param name="items">鍵值對,多個用\0分隔,形如key1=value1\0key2=value2</param>  
  219.     /// <returns></returns>  
  220.     public static bool INIWriteItems(string iniFile, string section, string items)  
  221.     {  
  222.         if (string.IsNullOrEmpty(section))  
  223.         {  
  224.             throw new ArgumentException("必須指定節點名稱", "section");  
  225.         }  
  226.   
  227.         if (string.IsNullOrEmpty(items))  
  228.         {  
  229.             throw new ArgumentException("必須指定鍵值對", "items");  
  230.         }  
  231.   
  232.         return INIOperationClass.WritePrivateProfileSection(section, items, iniFile);  
  233.     }  
  234.   
  235.     /// <summary>  
  236.     /// 在INI文件中,指定節點寫入指定的鍵及值。如果已經存在,則替換。如果沒有則創建。  
  237.     /// </summary>  
  238.     /// <param name="iniFile">INI文件</param>  
  239.     /// <param name="section">節點</param>  
  240.     /// <param name="key">鍵</param>  
  241.     /// <param name="value">值</param>  
  242.     /// <returns>操作是否成功</returns>  
  243.     public static bool INIWriteValue(string iniFile, string section, string key, string value)  
  244.     {  
  245.         if (string.IsNullOrEmpty(section))  
  246.         {  
  247.             throw new ArgumentException("必須指定節點名稱", "section");  
  248.         }  
  249.   
  250.         if (string.IsNullOrEmpty(key))  
  251.         {  
  252.             throw new ArgumentException("必須指定鍵名稱", "key");  
  253.         }  
  254.   
  255.         if (value == null)  
  256.         {  
  257.             throw new ArgumentException("值不能為null", "value");  
  258.         }  
  259.   
  260.         return INIOperationClass.WritePrivateProfileString(section, key, value, iniFile);  
  261.   
  262.     }  
  263.   
  264.     /// <summary>  
  265.     /// 在INI文件中,刪除指定節點中的指定的鍵。  
  266.     /// </summary>  
  267.     /// <param name="iniFile">INI文件</param>  
  268.     /// <param name="section">節點</param>  
  269.     /// <param name="key">鍵</param>  
  270.     /// <returns>操作是否成功</returns>  
  271.     public static bool INIDeleteKey(string iniFile, string section, string key)  
  272.     {  
  273.         if (string.IsNullOrEmpty(section))  
  274.         {  
  275.             throw new ArgumentException("必須指定節點名稱", "section");  
  276.         }  
  277.   
  278.         if (string.IsNullOrEmpty(key))  
  279.         {  
  280.             throw new ArgumentException("必須指定鍵名稱", "key");  
  281.         }  
  282.   
  283.         return INIOperationClass.WritePrivateProfileString(section, key, null, iniFile);  
  284.     }  
  285.   
  286.     /// <summary>  
  287.     /// 在INI文件中,刪除指定的節點。  
  288.     /// </summary>  
  289.     /// <param name="iniFile">INI文件</param>  
  290.     /// <param name="section">節點</param>  
  291.     /// <returns>操作是否成功</returns>  
  292.     public static bool INIDeleteSection(string iniFile, string section)  
  293.     {  
  294.         if (string.IsNullOrEmpty(section))  
  295.         {  
  296.             throw new ArgumentException("必須指定節點名稱", "section");  
  297.         }  
  298.   
  299.         return INIOperationClass.WritePrivateProfileString(section, null, null, iniFile);  
  300.     }  
  301.   
  302.     /// <summary>  
  303.     /// 在INI文件中,刪除指定節點中的所有內容。  
  304.     /// </summary>  
  305.     /// <param name="iniFile">INI文件</param>  
  306.     /// <param name="section">節點</param>  
  307.     /// <returns>操作是否成功</returns>  
  308.     public static bool INIEmptySection(string iniFile, string section)  
  309.     {  
  310.         if (string.IsNullOrEmpty(section))  
  311.         {  
  312.             throw new ArgumentException("必須指定節點名稱", "section");  
  313.         }  
  314.   
  315.         return INIOperationClass.WritePrivateProfileSection(section, string.Empty, iniFile);  
  316.     }  
  317.   
  318.   
  319.     private void TestIniINIOperation()  
  320.     {  
  321.   
  322.         string file = "F:\\TestIni.ini";  
  323.   
  324.         //寫入/更新鍵值  
  325.         INIWriteValue(file, "Desktop", "Color", "Red");  
  326.         INIWriteValue(file, "Desktop", "Width", "3270");  
  327.   
  328.         INIWriteValue(file, "Toolbar", "Items", "Save,Delete,Open");  
  329.         INIWriteValue(file, "Toolbar", "Dock", "True");  
  330.   
  331.         //寫入一批鍵值  
  332.         INIWriteItems(file, "Menu", "File=文件\0View=視圖\0Edit=編輯");  
  333.   
  334.         //獲取文件中所有的節點  
  335.         string[] sections = INIGetAllSectionNames(file);  
  336.   
  337.         //獲取指定節點中的所有項  
  338.         string[] items = INIGetAllItems(file, "Menu");  
  339.   
  340.         //獲取指定節點中所有的鍵  
  341.         string[] keys = INIGetAllItemKeys(file, "Menu");  
  342.   
  343.         //獲取指定KEY的值  
  344.         string value = INIGetStringValue(file, "Desktop", "color", null);  
  345.   
  346.         //刪除指定的KEY  
  347.         INIDeleteKey(file, "desktop", "color");  
  348.   
  349.         //刪除指定的節點  
  350.         INIDeleteSection(file, "desktop");  
  351.   
  352.         //清空指定的節點  
  353.         INIEmptySection(file, "toolbar");  
  354.   
  355.     }  
  356.     #endregion  
  357.  
  358.     #endregion  
  359. }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM