怎么在C#中对INI配置文件进行读写

发布时间:2021-03-05 17:21:25 作者:Leah
来源:亿速云 阅读:143

今天就跟大家聊聊有关怎么在C#中对INI配置文件进行读写,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于Xml的兴起,现在的配置文件大都是以xml文档来存储。比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介绍Remoting中提到的配置文件,都是xml的格式。

传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的。ini文件其实就是一个文本文件,它有固定的格式,节Section的名字用[]括起来,然后换行说明key的值:

[section]
key=value

如数据库服务器配置文件:

DBServer.ini

[Server]
Name=localhost
[DB]
Name=NorthWind
[User]
Name=sa

在C#中,对配置文件的读写是通过API函数来完成的,代码很简单:

using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace PubOp
{
  public class OperateIniFile
  {
    #region API函数声明
    [DllImport("kernel32")]//返回0表示失败,非0为成功
    private static extern long WritePrivateProfileString(string section,string key,
      string val,string filePath);
    [DllImport("kernel32")]//返回取得字符串缓冲区的长度
    private static extern long GetPrivateProfileString(string section,string key,
      string def,StringBuilder retVal,int size,string filePath);
    #endregion
    #region 读Ini文件
    public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
    {
      if(File.Exists(iniFilePath))
      {
        StringBuilder temp = new StringBuilder(1024);
        GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
        return temp.ToString();
      }
      else
      {
        return String.Empty;
      }
    }
    #endregion
    #region 写Ini文件
    public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
    {
      if(File.Exists(iniFilePath))
      {
        long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);  
        if(OpStation == 0)
        {
          return false;
        }
        else
        {
          return true;
        }
      }
      else
      {
        return false;
      }
    }
    #endregion
  }
}

简单说明以下方法WriteIniData()和ReadIniData()的参数。

Section参数、Key参数和IniFilePath不用再说,Value参数表明key的值,而这里的NoText对应API函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的Value时,就用NoText的值来代替。

 NoText 可以为null或""

看完上述内容,你们对怎么在C#中对INI配置文件进行读写有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. java 读写 ini配置文件
  2. goconfig如何对ini配置文件进行操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ni

上一篇:如何在springboot中实现多环境配置

下一篇:使用vue怎么实现配置多页面

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》