C#中写INI文件的方法

 因为要保存些软件的当前设置,又不想对系统有影响,(我想应该没人愿把自己的PC机当小白鼠,没事往里面写注册表玩吧),找了一下可以有两种方法解决

1.利用*.ini文件保存设置,读取方便,只是这种文件格式只被win98所提倡,NT 后都建议用注册表了!

2.利用*.xml文件进行保存,目前还不太了解,这两天学习一下再记录下来!

首先利用*.ini文件进行保存读写操作:

 

 

由于C#本身并不支持*.ini文件,所以要调用windows API 函数来进行读写

在网上找到了段代码,整理了一下如下:

1,命名空间中要加入以下引用:此命名空间具体干嘛的不懂,哪天有时间再说)

using System.Runtime.InteropServices;

2,winAPI函数声明:()   

     public partial class FORM1 : Form
        {
                //ini文件读写声明
                [DllImport("kernel32")]
                private static extern long WritePrivateProfileString(string section,
                 string key, string val, string filePath);
                [DllImport("kernel32")]
                private static extern int GetPrivateProfileString(string section,
                 string key, string def, StringBuilder retVal,
                 int size, string filePath);    

        }

3,我自己定义两个成员方法把API封装

 public void IniWrit_rue(string Section, string Key, string Value, string        
                                            filepath)                //     对ini文件进行写操作的函数
                {
                        WritePrivateProfileString(Section, Key, Value, filepath);
                }
                //读ini文件
                public string IniReadValue(string Section, string Key, string filepath)
                  //对ini文件进行读操作的函数
                {
                        StringBuilder temp = new StringBuilder(255);
                        int i = GetPrivateProfileString(Section, Key, "", temp,255, filepath);
                        return temp.ToString();
                }

4举例:

        //用按钮进行测试,在当前工程目录中的defaut.ini文件中写值

private void btn_test_Click(object sender, EventArgs e)
{
         tB_dipNum.Text = Directory.GetCurrentDirectory();//获取当前工程目录
         IniWrit_rue("ODBC 32 bit Data Sources", "MS Access Database", "because", 
                           Directory.GetCurrentDirectory() + "defaut.ini");//文件路径字段拼接
 }

 

 

posted @ 2012-07-28 22:42  璇星  阅读(983)  评论(0编辑  收藏  举报