C#读取.ini配置文件

**INI文件(Initialization File)**是一种简单的文本文件格式,用于存储程序的配置信息。在Visual Studio中,INI文件通常用于存储应用程序或项目的设置和配置数据。这些设置可能包括数据库连接字符串、应用程序参数、用户偏好等。

INI文件的结构由节(section)和键值对(key-value pair)组成。每个节都有一个唯一的名称,用于区分不同的配置区域。键值对则用于存储具体的配置项及其对应的值。例如:

复制代码
ini复制代码运行
[Database]
Server=localhost
DatabaseName=MyAppDB
UserID=admin
Password=123456   

在这个示例中,[Database]是一个节段Section,包含了与数据库相关的配置信息。接下来的键值对分别表示服务器地址、数据库名称、用户ID和密码

要在Visual Studio中使用INI文件,可以使用C#或其他编程语言提供的库来读取和写入这些文件。例如,使用C#的System.Configuration命名空间中的IniFile类可以方便地处理INI文件。

ini配置文件示例

复制代码
[database]  
host=localhost  
port=3306  
username=root  
password=mysecurepassword  
dbname=myappdb  

代码读取

复制代码
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        
/// <summary>
///读取ini文件数据
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="def">默认值</param>
/// <param name="filePath">文件路径</param>
/// <returns>读出内容</returns>
public static string ReadValueFromIniFile(string Section, string Key, string def, string filePath)
{
    StringBuilder temp = new StringBuilder(4096);
    int i = GetPrivateProfileString(Section, Key, def, temp, 4096, filePath);
    return temp.ToString();
}
 
/// <summary>
/// 写入数据到ini文件
/// </summary>
/// <param name="Section">段</param>
/// <param name="Key">键名</param>
/// <param name="Value">键值</param>
/// <param name="filePath">文件路径</param>
public static void WriteValueFromIniFile(string Section, string Key, string Value, string filePath)
{
    WritePrivateProfileString(Section, Key, Value, filePath);
}
相关推荐
薛定谔的算法15 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend16 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术17 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
小码编匠17 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
Raymond运维21 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉1 天前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
唐青枫1 天前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
RestCloud2 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud2 天前
为什么说零代码 ETL 是未来趋势?
数据库·api