C# 55. INI文件操作

//IniFileOp.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace xxxxx
{
    class IniFileOp
    {
        //#region 声明读写INI文件的API函数
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        //参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        //参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称
        //#endregion

        public string Path;

        public IniFileOp(string path)
        {
            this.Path = path;
        }


        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="section">段落</param>
        /// <param name="key">键</param>
        /// <param name="iValue">值</param>
        public void IniWriteStr(string section, string key, string iValue)
        {
            WritePrivateProfileString(section, key, iValue, this.Path);
        }

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">段落</param>
        /// <param name="key">键</param>
        /// <returns>返回的键值</returns>
        public string IniReadStr(string section, string key)
        {
            StringBuilder sb = new StringBuilder(256);

            int i = GetPrivateProfileString(section, key, "", sb, 256, this.Path);
            return sb.ToString();
        }

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">段,格式[]</param>
        /// <param name="Key">键</param>
        /// <returns>返回byte类型的section组或键值组</returns>
        public byte[] IniReadBytes(string section, string key)
        {
            StringBuilder sb = new StringBuilder(256);

            int i = GetPrivateProfileString(section, key, "", sb, 256, this.Path);
            string s = sb.ToString();
            byte[] byteArray = System.Text.Encoding.Default.GetBytes(s);
            return byteArray;
        }
    }
}

//ConfigPara.ini

[Param]
PauseTime=0

//使用

 int pauseTime = 0;

 string path1 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
 path1 += "ConfigPara.ini";
 IniFileOp inifile = new IniFileOp(path1);

 string str1 = inifile.IniReadStr("Param", "PauseTime");

 if (str1 != "")
 {
     pauseTime = int.Parse(str1);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值