zoukankan      html  css  js  c++  java
  • C# 操作ini配置文件

    最近使用Winform做一个小系统,由于需要保存一些默认配置项。自然就想到了轻量级的配置文件类型ini。在此也分享和记录一下实现方式,方便以后查询和使用。

    废话不多说上代码:

    实现公共函数↓

        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();
            }
        }

    调用实例↓

    //配置文件位置
    string configpath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
    //写入配置
    WinAPI.ProfileWriteValue("Setting", "DefaultSerialPort", ssp.SL_PortName, configpath);
    //读取配置
    WinAPI.ProfileReadValue("Setting", "DefaultSerialPort", configpath);

    初始化判断是否存在配置,否则创建文件↓

    //判断是否存在配置文件
    if
    (!File.Exists(configpath)) { FileStream fs = new FileStream(configpath, FileMode.OpenOrCreate); }
  • 相关阅读:
    java8时间处理
    HttpServletRequest
    Elasticsearch简介
    springCloud-Alibaba--Sentinel
    Nacos集群部署:
    nginx安装配置
    hibernate 嵌套事务
    linux下cmake安装mysql 源码
    linux下中文乱码问题解决
    tomcat quartz 被触发两次
  • 原文地址:https://www.cnblogs.com/wxlv/p/5446600.html
Copyright © 2011-2022 走看看