C#读写INI文件

这篇博客详细讲解了如何在C#中进行INI文件的读写操作,包括需要引入的命名空间、函数封装以及具体的数据读写示例。通过封装函数,可以提升C#项目的开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#读写INI文件



提示:以下是本篇文章正文内容,下面案例可供参考

一、命名空间

首先需要引用命名空间命名空间
using System.Runtime.InteropServices;

二、函数封装

代码如下(示例):

        [DllImport("kernel32")]
        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);

        #region   创建文件
        public static void CreateFile(string path)
        {
   
            if (!string.IsNullOrEmpty(path))
            {
   
                try
                {
   
                    string dr = Path.GetDirectoryName(path);

                    if (!Directory.Exists(dr))
                    {
   
                 
C#读写 INI 文件可以通过自定义方法或使用第三方库实现。INI 文件是一种常见的配置文件格式,结构简单、易于理解。 以下是通过编写代码手动操作 INI 文件的方式: ### 1. 使用 Windows API 操作 INI 文件 Windows 提供了 `GetPrivateProfileString` 和 `WritePrivateProfileString` 函数来处理 INI 配置文件。可以在 C# 程序中调用这些函数完成对 INI读写。 #### 示例代码: ```csharp using System; using System.Runtime.InteropServices; public class IniFileHandler { [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retval, int size, string filePath); [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string value, string filePath); public string FilePath { get; set; } // 构造函数初始化路径 public IniFileHandler(string iniFilePath) { this.FilePath = iniFilePath; } // 写入值到INI文件 public void WriteValue(string section, string key, string value) { WritePrivateProfileString(section, key, value, this.FilePath); } // 从INI文件读取指定键的值 public string ReadValue(string section, string key) { StringBuilder sb = new StringBuilder(256); // 定义缓冲区大小 int length = GetPrivateProfileString(section, key, "", sb, sb.Capacity, this.FilePath); return sb.ToString(); } } // 测试示例 class Program { static void Main() { var handler = new IniFileHandler(@"test.ini"); // 写入数据 handler.WriteValue("Section1", "Key1", "Value1"); // 读取数据 string readResult = handler.ReadValue("Section1", "Key1"); Console.WriteLine($"Read Value: {readResult}"); } } ``` --- ### 2. 自己解析字符串内容 (无依赖) 如果不想引入外部依赖项或者系统API,则可以将 `.ini` 视为普通的文本文件,并自行实现逻辑来加载和保存其中的内容。 #### 范例 - 手动读写 INI 文件 ```csharp System.Collections.Specialized.StringCollection settingsInIniFormat = new System.Collections.Specialized.StringCollection(); settingsInIniFormat.Add("[SectionA]"); settingsInIniFormat.Add("key=value"); ... ``` 然后逐行分析存储的数据并将其转换回字典形式等更易访问的形式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值