惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
S
SegmentFault 最新的问题
美团技术团队
博客园 - 【当耐特】
博客园_首页
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
Recent Announcements
Recent Announcements
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
量子位
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
Netflix TechBlog - Medium
大猫的无限游戏
大猫的无限游戏
F
Full Disclosure
Microsoft Security Blog
Microsoft Security Blog
Vercel News
Vercel News
G
Google Developers Blog
Last Week in AI
Last Week in AI
D
DataBreaches.Net
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
F
Fortinet All Blogs
宝玉的分享
宝玉的分享
雷峰网
雷峰网
罗磊的独立博客
V
V2EX
Recorded Future
Recorded Future
V
Visual Studio Blog
Y
Y Combinator Blog
T
Tailwind CSS Blog
小众软件
小众软件
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
U
Unit 42

博客园 - playman0211

UE蓝图---实现场景物体Transform状态重置效果 【转】读取系统时间和时间戳【UE4】【C++】 关于Unity中关节的使用(一) Unity --- 关节组件 C# CRC16算法实现【转】 IhyerDB modBus采集器配置. 简单理解C#中的抽象工厂模式是什么概念! C# 进制转换(二进制、十六进制、十进制互转) 软件加密锁编程技巧【转】 C#按回车Enter使输入焦点自动跳到下一个TextBox的方法收集 Gjhf c#格式化数字(转) oracle数据库删除数据Delete语句和Truncate语句的对比 用Instant client批量安装Oracle客户端-安装配置 C#使用instantclient连接 Oracle 10g (转) InstantClient安装使用 (转) oracle case when的使用方法 Oracle case when 用法(转) SQL Server CONVERT() 函数
C# 读写ini文件 【转】
playman0211 · 2013-01-14 · via 博客园 - playman0211

在做项目过程中,有时需要保存一些简单的配置信息,可以使用xml,也可以使用INI文件。下面是C#中读取INI的方法,相信大部分朋友都使用过这种方式。 INI文件的存储方式如下,

  1. [section] 
  2. key=value 
  3. key=value 
[section]
key=value
key=value

读取写入方法,

  1. [DllImport("kernel32")] 
  2. privatestaticexternlong WritePrivateProfileString(string section, string key, string val, string filePath); 
  3.  
  4. [DllImport("kernel32")] 
  5. privatestaticexternint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName); 
  6.  
  7. [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  8. privatestaticexternuint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName); 
  9.  
  10. privatestaticstring ReadString(string section, string key, string def, string filePath) 
  11.     StringBuilder temp = new StringBuilder(1024); 
  12.  
  13.     try 
  14.     { 
  15.         GetPrivateProfileString(section, key, def, temp, 1024, filePath); 
  16.     } 
  17.     catch 
  18.     { } 
  19.     return temp.ToString(); 
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26. publicstaticstring[] ReadIniAllKeys(string section,string filePath) 
  27.     UInt32 MAX_BUFFER = 32767;   
  28.  
  29.     string[] items = newstring[0];   
  30.  
  31.     IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); 
  32.  
  33.     UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath); 
  34.  
  35.     if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0)) 
  36.     { 
  37.         string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned); 
  38.  
  39.         items = returnedString.Split(newchar[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); 
  40.     } 
  41.  
  42.     Marshal.FreeCoTaskMem(pReturnedString);  
  43.  
  44.     return items; 
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53. publicstaticstring ReadIniKeys(string section, string keys, string filePath) 
  54.     return ReadString(section, keys, "", filePath); 
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63. publicstaticvoid WriteIniKeys(string section, string key, string value, string filePath) 
  64.     WritePrivateProfileString(section, key, value, filePath); 
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);

        private static string ReadString(string section, string key, string def, string filePath)
        {
            StringBuilder temp = new StringBuilder(1024);

            try
            {
                GetPrivateProfileString(section, key, def, temp, 1024, filePath);
            }
            catch
            { }
            return temp.ToString();
        }
        /// <summary>
        /// 根据section取所有key
        /// </summary>
        /// <param name="section"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string[] ReadIniAllKeys(string section,string filePath)
        {
            UInt32 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[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Marshal.FreeCoTaskMem(pReturnedString); 

            return items;
        }

        /// <summary>
        /// 根据section,key取值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="keys"></param>
        /// <param name="filePath">ini文件路径</param>
        /// <returns></returns>
        public static string ReadIniKeys(string section, string keys, string filePath)
        {
            return ReadString(section, keys, "", filePath);
        }

        /// <summary>
        /// 保存ini
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filePath">ini文件路径</param>
        public static void WriteIniKeys(string section, string key, string value, string filePath)
        {
            WritePrivateProfileString(section, key, value, filePath);
        }

如果要删除某一项:

  1. WriteIniKeys(section, key, null, recordIniPath); 
WriteIniKeys(section, key, null, recordIniPath);

如上就可以读取和写入了,那么INI文件如何创建呢?

  1. [DllImport("kernel32")] 
  2. publicstaticexternlong WritePrivateProfileString(string section, string key, string value, string iniPath); 
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string value, string iniPath);

调用该方法,即可创建你的ini文件和想要保存的值。

当然上面的ini操作并不是很详细的,以下从http://blog.csdn.net/sdfkfkd/article/details/7050733的博客转载的一片描述INI操作的,比较详细,值得学习。

  1. publicclass INIOperationClass 
  2. {
  3.     #region INI文件操作  
  4.  
  5.    
  6.     #region API声明  
  7.  
  8.      
  9.      
  10.      
  11.      
  12.      
  13.      
  14.      
  15.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  16.     privatestaticexternuint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName); 
  17.  
  18.      
  19.      
  20.      
  21.      
  22.      
  23.      
  24.      
  25.      
  26.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  27.     privatestaticexternuint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName); 
  28.  
  29.      
  30.      
  31.      
  32.      
  33.      
  34.      
  35.      
  36.      
  37.      
  38.      
  39.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  40.     privatestaticexternuint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName); 
  41.  
  42.      
  43.      
  44.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  45.     privatestaticexternuint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); 
  46.  
  47.      
  48.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  49.     privatestaticexternuint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName); 
  50.  
  51.      
  52.      
  53.      
  54.      
  55.      
  56.      
  57.      
  58.      
  59.      
  60.      
  61.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
  62.     [return: MarshalAs(UnmanagedType.Bool)]      
  63.     privatestaticexternbool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName); 
  64.  
  65.      
  66.      
  67.      
  68.      
  69.      
  70.      
  71.      
  72.      
  73.     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
  74.     [return: MarshalAs(UnmanagedType.Bool)] 
  75.     privatestaticexternbool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
  76.     #endregion
  77.     #region 封装  
  78.  
  79.      
  80.      
  81.      
  82.      
  83.      
  84.     publicstaticstring[] INIGetAllSectionNames(string iniFile) 
  85.     { 
  86.         uint MAX_BUFFER = 32767;     
  87.  
  88.         string[] sections = newstring[0];       
  89.  
  90.          
  91.         IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); 
  92.         uint bytesReturned = INIOperationClass.GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile); 
  93.         if (bytesReturned != 0) 
  94.         { 
  95.              
  96.             string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString(); 
  97.  
  98.              
  99.             sections = local.Split(newchar[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); 
  100.         } 
  101.  
  102.          
  103.         Marshal.FreeCoTaskMem(pReturnedString); 
  104.  
  105.         return sections; 
  106.     } 
  107.  
  108.      
  109.      
  110.      
  111.      
  112.      
  113.      
  114.     publicstaticstring[] INIGetAllItems(string iniFile, string section) 
  115.     { 
  116.          
  117.         uint MAX_BUFFER = 32767;     
  118.  
  119.         string[] items = newstring[0];       
  120.  
  121.          
  122.         IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); 
  123.  
  124.         uint bytesReturned = INIOperationClass.GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile); 
  125.  
  126.         if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0)) 
  127.         { 
  128.  
  129.             string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned); 
  130.             items = returnedString.Split(newchar[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); 
  131.         } 
  132.  
  133.         Marshal.FreeCoTaskMem(pReturnedString);      
  134.  
  135.         return items; 
  136.     } 
  137.  
  138.      
  139.      
  140.      
  141.      
  142.      
  143.      
  144.     publicstaticstring[] INIGetAllItemKeys(string iniFile, string section) 
  145.     { 
  146.         string[] value = newstring[0]; 
  147.         constint SIZE = 1024 * 10; 
  148.  
  149.         if (string.IsNullOrEmpty(section)) 
  150.         { 
  151.             thrownew ArgumentException("必须指定节点名称", "section"); 
  152.         } 
  153.  
  154.         char[] chars = newchar[SIZE]; 
  155.         uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, null, null, chars, SIZE, iniFile); 
  156.  
  157.         if (bytesReturned != 0) 
  158.         { 
  159.             value = newstring(chars).Split(newchar[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); 
  160.         } 
  161.         chars = null
  162.  
  163.         return value; 
  164.     } 
  165.  
  166.      
  167.      
  168.      
  169.      
  170.      
  171.      
  172.      
  173.      
  174.     publicstaticstring INIGetStringValue(string iniFile, string section, string key, string defaultValue) 
  175.     { 
  176.         string value = defaultValue; 
  177.         constint SIZE = 1024 * 10; 
  178.  
  179.         if (string.IsNullOrEmpty(section)) 
  180.         { 
  181.             thrownew ArgumentException("必须指定节点名称", "section"); 
  182.         } 
  183.  
  184.         if (string.IsNullOrEmpty(key)) 
  185.         { 
  186.             thrownew ArgumentException("必须指定键名称(key)", "key"); 
  187.         } 
  188.  
  189.         StringBuilder sb = new StringBuilder(SIZE); 
  190.         uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile); 
  191.  
  192.         if (bytesReturned != 0) 
  193.         { 
  194.             value = sb.ToString(); 
  195.         } 
  196.         sb = null
  197.  
  198.         return value; 
  199.     } 
  200.  
  201.      
  202.      
  203.      
  204.      
  205.      
  206.      
  207.      
  208.     publicstaticbool INIWriteItems(string iniFile, string section, string items) 
  209.     { 
  210.         if (string.IsNullOrEmpty(section)) 
  211.         { 
  212.             thrownew ArgumentException("必须指定节点名称", "section"); 
  213.         } 
  214.  
  215.         if (string.IsNullOrEmpty(items)) 
  216.         { 
  217.             thrownew ArgumentException("必须指定键值对", "items"); 
  218.         } 
  219.  
  220.         return INIOperationClass.WritePrivateProfileSection(section, items, iniFile); 
  221.     } 
  222.  
  223.      
  224.      
  225.      
  226.      
  227.      
  228.      
  229.      
  230.      
  231.     publicstaticbool INIWriteValue(string iniFile, string section, string key, string value) 
  232.     { 
  233.         if (string.IsNullOrEmpty(section)) 
  234.         { 
  235.             thrownew ArgumentException("必须指定节点名称", "section"); 
  236.         } 
  237.  
  238.         if (string.IsNullOrEmpty(key)) 
  239.         { 
  240.             thrownew ArgumentException("必须指定键名称", "key"); 
  241.         } 
  242.  
  243.         if (value == null
  244.         { 
  245.             thrownew ArgumentException("值不能为null", "value"); 
  246.         } 
  247.  
  248.         return INIOperationClass.WritePrivateProfileString(section, key, value, iniFile); 
  249.  
  250.     } 
  251.  
  252.      
  253.      
  254.      
  255.      
  256.      
  257.      
  258.      
  259.     publicstaticbool INIDeleteKey(string iniFile, string section, string key) 
  260.     { 
  261.         if (string.IsNullOrEmpty(section)) 
  262.         { 
  263.             thrownew ArgumentException("必须指定节点名称", "section"); 
  264.         } 
  265.  
  266.         if (string.IsNullOrEmpty(key)) 
  267.         { 
  268.             thrownew ArgumentException("必须指定键名称", "key"); 
  269.         } 
  270.  
  271.         return INIOperationClass.WritePrivateProfileString(section, key, null, iniFile); 
  272.     } 
  273.  
  274.      
  275.      
  276.      
  277.      
  278.      
  279.      
  280.     publicstaticbool INIDeleteSection(string iniFile, string section) 
  281.     { 
  282.         if (string.IsNullOrEmpty(section)) 
  283.         { 
  284.             thrownew ArgumentException("必须指定节点名称", "section"); 
  285.         } 
  286.  
  287.         return INIOperationClass.WritePrivateProfileString(section, null, null, iniFile); 
  288.     } 
  289.  
  290.      
  291.      
  292.      
  293.      
  294.      
  295.      
  296.     publicstaticbool INIEmptySection(string iniFile, string section) 
  297.     { 
  298.         if (string.IsNullOrEmpty(section)) 
  299.         { 
  300.             thrownew ArgumentException("必须指定节点名称", "section"); 
  301.         } 
  302.  
  303.         return INIOperationClass.WritePrivateProfileSection(section, string.Empty, iniFile); 
  304.     } 
  305.  
  306.  
  307.     privatevoid TestIniINIOperation() 
  308.     { 
  309.  
  310.         string file = "F:\\TestIni.ini"
  311.  
  312.          
  313.         INIWriteValue(file, "Desktop", "Color", "Red"); 
  314.         INIWriteValue(file, "Desktop", "Width", "3270"); 
  315.  
  316.         INIWriteValue(file, "Toolbar", "Items", "Save,Delete,Open"); 
  317.         INIWriteValue(file, "Toolbar", "Dock", "True"); 
  318.  
  319.          
  320.         INIWriteItems(file, "Menu", "File=文件\0View=视图\0Edit=编辑"); 
  321.  
  322.          
  323.         string[] sections = INIGetAllSectionNames(file); 
  324.  
  325.          
  326.         string[] items = INIGetAllItems(file, "Menu"); 
  327.  
  328.          
  329.         string[] keys = INIGetAllItemKeys(file, "Menu"); 
  330.  
  331.          
  332.         string value = INIGetStringValue(file, "Desktop", "color", null); 
  333.  
  334.          
  335.         INIDeleteKey(file, "desktop", "color"); 
  336.  
  337.          
  338.         INIDeleteSection(file, "desktop"); 
  339.  
  340.          
  341.         INIEmptySection(file, "toolbar"); 
  342.  
  343.     }
  344.     #endregion
  345.     #endregion  
    public class INIOperationClass
    {

        #region INI文件操作

        /*
         * 针对INI文件的API操作方法,其中的节点(Section)、键(KEY)都不区分大小写
         * 如果指定的INI文件不存在,会自动创建该文件。
         * 
         * CharSet定义的时候使用了什么类型,在使用相关方法时必须要使用相应的类型
         *      例如 GetPrivateProfileSectionNames声明为CharSet.Auto,那么就应该使用 Marshal.PtrToStringAuto来读取相关内容
         *      如果使用的是CharSet.Ansi,就应该使用Marshal.PtrToStringAnsi来读取内容
         *      
         */

        #region API声明

        /// <summary>
        /// 获取所有节点名称(Section)
        /// </summary>
        /// <param name="lpszReturnBuffer">存放节点名称的内存地址,每个节点之间用\0分隔</param>
        /// <param name="nSize">内存大小(characters)</param>
        /// <param name="lpFileName">Ini文件</param>
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

        private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);

        /// <summary>
        /// 获取某个指定节点(Section)中所有KEY和Value
        /// </summary>
        /// <param name="lpAppName">节点名称</param>
        /// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>
        /// <param name="nSize">内存大小(characters)</param>
        /// <param name="lpFileName">Ini文件</param>
        /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);

        /// <summary>
        /// 读取INI文件中指定的Key的值
        /// </summary>
        /// <param name="lpAppName">节点名称。如果为null,则读取INI中所有节点名称,每个节点名称之间用\0分隔</param>
        /// <param name="lpKeyName">Key名称。如果为null,则读取INI中指定节点中的所有KEY,每个KEY之间用\0分隔</param>
        /// <param name="lpDefault">读取失败时的默认值</param>
        /// <param name="lpReturnedString">读取的内容缓冲区,读取之后,多余的地方使用\0填充</param>
        /// <param name="nSize">内容缓冲区的长度</param>
        /// <param name="lpFileName">INI文件名</param>
        /// <returns>实际读取到的长度</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);

        //另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符,会将\0及其后的字符截断,
        //所以对于lpAppName或lpKeyName为null的情况就不适用
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);

        //再一种声明,使用string作为缓冲区的类型同char[]
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName);

        /// <summary>
        /// 将指定的键值对写到指定的节点,如果已经存在则替换。
        /// </summary>
        /// <param name="lpAppName">节点,如果不存在此节点,则创建此节点</param>
        /// <param name="lpString">Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
        /// <para>如果为string.Empty,则删除指定节点下的所有内容,保留节点</para>
        /// <para>如果为null,则删除指定节点下的所有内容,并且删除该节点</para>
        /// </param>
        /// <param name="lpFileName">INI文件</param>
        /// <returns>是否成功写入</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]     //可以没有此行
        private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);

        /// <summary>
        /// 将指定的键和值写到指定的节点,如果已经存在则替换
        /// </summary>
        /// <param name="lpAppName">节点名称</param>
        /// <param name="lpKeyName">键名称。如果为null,则删除指定的节点及其所有的项目</param>
        /// <param name="lpString">值内容。如果为null,则删除指定节点中指定的键。</param>
        /// <param name="lpFileName">INI文件</param>
        /// <returns>操作是否成功</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

        #endregion

        #region 封装

        /// <summary>
        /// 读取INI文件中指定INI文件中的所有节点名称(Section)
        /// </summary>
        /// <param name="iniFile">Ini文件</param>
        /// <returns>所有节点,没有内容返回string[0]</returns>
        public static string[] INIGetAllSectionNames(string iniFile)
        {
            uint MAX_BUFFER = 32767;    //默认为32767

            string[] sections = new string[0];      //返回值

            //申请内存
            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
            uint bytesReturned = INIOperationClass.GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
            if (bytesReturned != 0)
            {
                //读取指定内存的内容
                string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();

                //每个节点之间用\0分隔,末尾有一个\0
                sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            //释放内存
            Marshal.FreeCoTaskMem(pReturnedString);

            return sections;
        }

        /// <summary>
        /// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)
        /// </summary>
        /// <param name="iniFile">Ini文件</param>
        /// <param name="section">节点名称</param>
        /// <returns>指定节点中的所有项目,没有内容返回string[0]</returns>
        public static string[] INIGetAllItems(string iniFile, string section)
        {
            //返回值形式为 key=value,例如 Color=Red
            uint MAX_BUFFER = 32767;    //默认为32767

            string[] items = new string[0];      //返回值

            //分配内存
            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[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Marshal.FreeCoTaskMem(pReturnedString);     //释放内存

            return items;
        }

        /// <summary>
        /// 获取INI文件中指定节点(Section)中的所有条目的Key列表
        /// </summary>
        /// <param name="iniFile">Ini文件</param>
        /// <param name="section">节点名称</param>
        /// <returns>如果没有内容,反回string[0]</returns>
        public static string[] INIGetAllItemKeys(string iniFile, string section)
        {
            string[] value = new string[0];
            const int SIZE = 1024 * 10;

            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "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[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            chars = null;

            return value;
        }

        /// <summary>
        /// 读取INI文件中指定KEY的字符串型值
        /// </summary>
        /// <param name="iniFile">Ini文件</param>
        /// <param name="section">节点名称</param>
        /// <param name="key">键名称</param>
        /// <param name="defaultValue">如果没此KEY所使用的默认值</param>
        /// <returns>读取到的值</returns>
        public static string INIGetStringValue(string iniFile, string section, string key, string defaultValue)
        {
            string value = defaultValue;
            const int SIZE = 1024 * 10;

            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称(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>
        /// 在INI文件中,将指定的键值对写到指定的节点,如果已经存在则替换
        /// </summary>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点,如果不存在此节点,则创建此节点</param>
        /// <param name="items">键值对,多个用\0分隔,形如key1=value1\0key2=value2</param>
        /// <returns></returns>
        public static bool INIWriteItems(string iniFile, string section, string items)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            if (string.IsNullOrEmpty(items))
            {
                throw new ArgumentException("必须指定键值对", "items");
            }

            return INIOperationClass.WritePrivateProfileSection(section, items, iniFile);
        }

        /// <summary>
        /// 在INI文件中,指定节点写入指定的键及值。如果已经存在,则替换。如果没有则创建。
        /// </summary>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>操作是否成功</returns>
        public static bool INIWriteValue(string iniFile, string section, string key, string value)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }

            if (value == null)
            {
                throw new ArgumentException("值不能为null", "value");
            }

            return INIOperationClass.WritePrivateProfileString(section, key, value, iniFile);

        }

        /// <summary>
        /// 在INI文件中,删除指定节点中的指定的键。
        /// </summary>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>
        /// <param name="key">键</param>
        /// <returns>操作是否成功</returns>
        public static bool INIDeleteKey(string iniFile, string section, string key)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }

            return INIOperationClass.WritePrivateProfileString(section, key, null, iniFile);
        }

        /// <summary>
        /// 在INI文件中,删除指定的节点。
        /// </summary>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>
        /// <returns>操作是否成功</returns>
        public static bool INIDeleteSection(string iniFile, string section)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            return INIOperationClass.WritePrivateProfileString(section, null, null, iniFile);
        }

        /// <summary>
        /// 在INI文件中,删除指定节点中的所有内容。
        /// </summary>
        /// <param name="iniFile">INI文件</param>
        /// <param name="section">节点</param>
        /// <returns>操作是否成功</returns>
        public static bool INIEmptySection(string iniFile, string section)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            return INIOperationClass.WritePrivateProfileSection(section, string.Empty, iniFile);
        }


        private void TestIniINIOperation()
        {

            string file = "F:\\TestIni.ini";

            //写入/更新键值
            INIWriteValue(file, "Desktop", "Color", "Red");
            INIWriteValue(file, "Desktop", "Width", "3270");

            INIWriteValue(file, "Toolbar", "Items", "Save,Delete,Open");
            INIWriteValue(file, "Toolbar", "Dock", "True");

            //写入一批键值
            INIWriteItems(file, "Menu", "File=文件\0View=视图\0Edit=编辑");

            //获取文件中所有的节点
            string[] sections = INIGetAllSectionNames(file);

            //获取指定节点中的所有项
            string[] items = INIGetAllItems(file, "Menu");

            //获取指定节点中所有的键
            string[] keys = INIGetAllItemKeys(file, "Menu");

            //获取指定KEY的值
            string value = INIGetStringValue(file, "Desktop", "color", null);

            //删除指定的KEY
            INIDeleteKey(file, "desktop", "color");

            //删除指定的节点
            INIDeleteSection(file, "desktop");

            //清空指定的节点
            INIEmptySection(file, "toolbar");

        }
        #endregion

        #endregion
    }

 来自:http://blog.csdn.net/yysyangyangyangshan/article/details/7017523