用ini文件实现数据库的增、删、改、查

本文以C#为例,这些函数本身就是C++的api

1.函数引入(以string操作为例)

具体函数的参数不再做详细介绍,可以自己去查msdn

//获取指定section中指定key的值

[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal,int size, string filePath);

 

//设置指定section中指定key的值

[DllImport("kernel32.dll")]
private static extern int WritePrivateProfileString(string lpApplicationName,string lpKeyName, string def, string lpFileName);

 

//获取ini文件中所有的section的name,注意,这些name不是以字符串格式返回,而是byte格式的数组

[DllImport("kernel32.dll")]
public static extern int GetPrivateProfileSectionNames(byte[] buffer,int iLen, string lpFileName);

函数封装实例:

       //注意获取指定ini文件中的section的name放在一个ArrayList中返回

       public ArrayList ReadSections(string FileName)
        {
            byte[] buffer = new byte[65535];
            int rel = GetPrivateProfileSectionNames(buffer, buffer.GetUpperBound(0), FileName);
            return Conver2ArrayList(rel, buffer);
        }
        //这个函数的第一个参数就是GetPrivateProfileSectionNames的返回值,第二个参数就是section的name所组成的byte数组,即GetPrivateProfileSectionNames的第一个参数
        public ArrayList Conver2ArrayList(int rel, byte[] buffer)
        {
            ArrayList arrayList = new ArrayList();
            if (rel > 0)
            {
                int iCnt, iPos;
                string tmp;
                iCnt = 0; iPos = 0;
                for (iCnt = 0; iCnt < rel; iCnt++)
                {
                    if (buffer[iCnt] == 0x00)
                    {
                        tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
                        iPos = iCnt + 1;
                        if (tmp != "")
                            arrayList.Add(tmp);
                    }
                }
            }
            return arrayList;
        }

2.实现"增"的功能,假如我们的ini文件是在C:\下的test.ini

我们要在section1下增加一个key1,它的值为hello,(section1也可以不存在)

WritePrivateProfileString(“section1”, "key1", “hello”, @"C:\test.ini");

 

3.实现”删“的功能

如果要删除整个”section1“节点,如下

WritePrivateProfileString(”section1“, null, null, @"C:\1.ini");

 

如果要删除”section1“下的”key1“,如下

WritePrivateProfileString(”section1“, "key1", null, @"C:\1.ini");

 

4.实现"改"的功能

如果我们要将”section1“下的"key1“的值改为"word“,其实它就是"增",只是覆盖了原来的内容而已

WritePrivateProfileString(”section1“, "key1", ”word“, @"C:\1.ini");

 

5.实现 "查"的功能

如果要获取”section1“下的”key1“的内容,如下

GetPrivateProfileString("section1“, "key1", "FFFF", str1, 255, @"C:\1.ini");

 

以上就是全部内容,当我们想要对很小的资料进行维护的时候而你又不会或者没有条件使用数据库,就能用以上方法实现类似数据库的操作

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

血虐丘比特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值