请选择 进入手机版 | 继续访问电脑版

马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#操作ini配置文件代码【转】

[复制链接]
查看4233 | 回复3 | 2017-3-22 09:25:17 | 显示全部楼层 |阅读模式
最近使用Winform做一个小系统,由于需要保存一些默认配置项。自然就想到了轻量级的配置文件类型ini。在此也分享和记录一下实现方式,方便以后查询和使用。

废话不多说上代码:

实现公共函数↓
[C#] 纯文本查看 复制代码


public static class WinAPI
    {
        [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);
        // 向配置文件写入值
        public static void ProfileWriteValue(
        string section, string key, string value, string path)
        {
            WritePrivateProfileString(section, key, value, path);
        }
        // 读取配置文件的值
        public static string ProfileReadValue(
        string section, string key, string path)
        {
            StringBuilder sb = new StringBuilder(255);
            GetPrivateProfileString(section, key, "", sb, 255, path);
            return sb.ToString().Trim();
        }
    }


调用实例↓

[C#] 纯文本查看 复制代码
//配置文件位置
string configpath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
//写入配置
WinAPI.ProfileWriteValue("Setting", "DefaultSerialPort", ssp.SL_PortName, configpath);
//读取配置
WinAPI.ProfileReadValue("Setting", "DefaultSerialPort", configpath);


初始化判断是否存在配置,否则创建文件↓
[C#] 纯文本查看 复制代码
//判断是否存在配置文件
if (!File.Exists(configpath))
{
   FileStream fs = new FileStream(configpath, FileMode.OpenOrCreate);
}


C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
ibcadmin | 2017-3-22 09:26:20 | 显示全部楼层
11
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
Amy尾巴 | 2017-3-22 09:27:46 | 显示全部楼层
22
擎天柱 | 2017-3-22 09:37:49 来自手机 | 显示全部楼层
要要要
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则