首页 > 代码库 > 读写INI文件操作类

读写INI文件操作类

IniHelper 类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;namespace SingleStore.Code{    public class IniHelper    {        // 声明INI文件的写操作函数 WritePrivateProfileString()        [DllImport("kernel32")]        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);        // 声明INI文件的读操作函数 GetPrivateProfileString()        [DllImport("kernel32")]        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);        //获取ini文件的路径        private string sPath = null;        public IniHelper(string path)        {            this.sPath = path;        }        /// <summary>        /// 写入INI文件        /// </summary>        /// <param name="section">配置节</param>        /// <param name="key">键名</param>        /// <param name="value">键值</param>        public void WriteValue(string section, string key, string value)        {            // section=配置节,key=键名,value=http://www.mamicode.com/键值,path=路径            WritePrivateProfileString(section, key, value, sPath);        }        /// <summary>        /// 读取INI文件配置节下的键        /// </summary>        /// <param name="section"></param>        /// <param name="key"></param>        /// <returns></returns>        public string ReadValue(string section, string key)        {            // 每次从ini中读取多少字节            StringBuilder temp = new StringBuilder(255);            // section=配置节,key=键名,temp=上面,path=路径            GetPrivateProfileString(section,key,"",temp,255,sPath);            return temp.ToString();        }    }}

 

Form窗体调用

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using SingleStore.Code;namespace SingleStore{    public partial class Login : Form    {        public Login()        {            InitializeComponent();            string IniPath = Directory.GetCurrentDirectory();            //写入ini            IniHelper ini = new IniHelper(IniPath + "/config.ini");            ini.WriteValue("StoreShop", "userName", "admin");            ini.WriteValue("StoreShop", "pwd", "admin");            ini.WriteValue("StoreShop", "isRePwd", "0");            //读取ini            string ispwd = ini.ReadValue("StoreShop", "isRePwd");            string xis = "";            if (ispwd == "0")            {                xis = "";            }            else            {                xis = "";            }            MessageBox.Show("用户名:" + ini.ReadValue("StoreShop", "userName") + "\n" +                "密码:" + ini.ReadValue("StoreShop", "pwd") + "\n" +                "是否记住密码:" + xis);        }    }}

读写INI文件操作类