• 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");//文件路径字段拼接
     }

     

        
    作者:wanglei_wan
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    后渗透
    Msf小结
    安全狗文件绕过
    文件上传漏洞
    SQL Injection(Blind)
    SQL Injection
    Linux 基础整理
    Python pip升级及升级失败解决方案
    文件包含
    信息收集
  • 原文地址:https://www.cnblogs.com/because/p/2613644.html
Copyright © 2020-2023  润新知