c#如何读取ini文件一个键值下的所有值

API调用

最近在学习c#,我用的是api申明的方法,先创建一个类,详情如下:

 #region API声明


        /// 获取所有节点名称(Section)

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


        /// 获取某个指定节点(Section)中所有KEY和Value

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


        /// 读取INI文件中指定的Key的值

        [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);


        /// 将指定的键值对写到指定的节点,如果已经存在则替换。

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]     //可以没有此行
        private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);


        /// 将指定的键和值写到指定的节点,如果已经存在则替换

        [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 封装


        /// 读取INI文件中指定INI文件中的所有节点名称(Section)

        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 = Win32API.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;
        }



 
        /// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)

        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 = Win32API.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;
        }



        /// 获取INI文件中指定节点(Section)中的所有条目的Key列表

        public static string[] INIGetAllItemKeys(string iniFile, string section)
        {
            const int SIZE = 1024 * 10;    //默认为32767
            string[] value = new string[0];
            char[] chars = new char[SIZE];   //返回值

         
            uint bytesReturned = Win32API.GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);
            if (bytesReturned != 0)
            {
                value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            chars = null;


            return value;
        }

    


        // 读取INI文件中指定KEY的字符串型值

        public static string[] INIGetStringValue(string iniFile, string section, string key, string defaultValue)
        {
            string[] value = new string[0];
            const int SIZE = 1024 * 10;

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

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称(key)", "key");
            }
            char[] chars = new char[SIZE];
            uint bytesReturned = Win32API.GetPrivateProfileString(section, key, defaultValue, chars, SIZE, iniFile);


            if (bytesReturned != 0)
            {
                value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }
            chars = null;

            return value;
        }
        //读取section中单个value
        public static string INIGetStringValue1(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 = GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile);

            if (bytesReturned != 0)
            {
                value = sb.ToString();
            }
            sb = null;
            return value;
        }

接着再winform中写入代码,我用的access数据库

string file = "F:\\project\\INIReader2.2\\form1\\bin\\Debug\\SysConfig.ini";
string Con = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=F:/access/first1.mdb";
//button代码如下:
string s = textBox1.Text;
 string[] sections = Win32API.INIGetAllSectionNames(file);

                for (int k = 0; k < sections.Length; k++)
                {
                    //获取指定节点中所有的键
                    string[] keys = Win32API.INIGetAllItemKeys(file, s);
                    for (int j = 0; j < keys.Length; j++)
                    {
                        //获取指定KEY的值
                        string[] value = Win32API.INIGetStringValue(file, s, keys[j], null);
                        OleDbConnection con = new OleDbConnection(Con);
                        con.Open();

                        OleDbCommand cmd = new OleDbCommand();
                        cmd.Connection = con;
                        cmd.Transaction = con.BeginTransaction();

                        try
                        {

                            string sql1 = "INSERT INTO  AAAA追溯及二维码表(ID,设置项,值) values('" + j + "','" + keys[j] + "','" + value[k] + "')";

                            string[] SQLStringList = { sql1 };
                            for (int i = 0; i < SQLStringList.Length; i++)
                            {
                                string strsql = SQLStringList[i].ToString();
                                if (strsql.Trim().Length > 1)
                                {
                                    cmd.CommandText = strsql;
                                    cmd.ExecuteNonQuery();
                                }
                            }
                            cmd.Transaction.Commit();  //提交事务

                        }
                        catch (Exception)
                        {
                            cmd.Transaction.Rollback();
                        }
                        finally
                        {
                            con.Close();
                        }

                    }

                }
                if (sections.Length >= 1) { MessageBox.Show("成功添加数据!"); }
                else { MessageBox.Show("添加失败!"); }

这就可以得到一个section下所有的数据了!

  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值