C# 读取ini文件

ini文件介绍

ini文件是微软操作系统上的配置文件,格式如下

 

;此处是注释

[section1]

key1=value1

key2=value2

[section2]

key3=value3

 

注意: 注释符号为分号

 

 

 

 

 

c#操作ini文件的类

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

        public class Ini
        {
            // 声明INI文件的写操作函数 WritePrivateProfileString()

            [System.Runtime.InteropServices.DllImport("kernel32")]

            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

            // 声明INI文件的读操作函数 GetPrivateProfileString()

            [System.Runtime.InteropServices.DllImport("kernel32")]

            private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

            private string sPath = null;
            public Ini(string path)
            {
                this.sPath = path;
            }

            public void Writue(string section, string key, string value)
            {

                // section=配置节,key=键名,value=键值,path=路径

                WritePrivateProfileString(section, key, value, sPath);

            }
            public string ReadValue(string section, string key)
            {

                // 每次从ini中读取多少字节

                System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

                // section=配置节,key=键名,temp=上面,path=路径

                GetPrivateProfileString(section, key, "", temp, 255, sPath);

                return temp.ToString();

            }

        }
    }

 

 

 

操作ini文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            string Current;

            Current = Directory.GetCurrentDirectory();//获取当前根目录

            Ini ini = new Ini(Current + "/config.ini");
            ini.Writue("Setting", "key1", "hello word!");      //写入ini文件
            ini.Writue("Setting", "key2", "hello ini!");
            ini.Writue("SettingImg", "Path", "IMG.Path");

            string stemp = ini.ReadValue("Setting", "key2");//读取Setting章节的key2值
            MessageBox.Show(stemp);  //hello ini!
        }
    }
}

 

 

打开项目路径中的config.ini文件查看内容应该如下

 

[Setting]
key1=hello word!
key2=hello ini!
[SettingImg]
Path=IMG.Path

posted on 2014-01-05 20:16 水墨.MR.H 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/StudyLife/p/3506213.html

<think>我们被要求使用C#读取INI文件。根据引用,我们可以看到几个关键点: 1. 引用[1]提到C#读取ini文件、键值对操作,并提到虽然微软推荐使用注册表或.NET配置文件,但有时仍会使用INI。 2. 引用[2]和[3]提供了具体的代码示例,包括写INI文件和读INI文件的方法。 3. 引用[4]也提到了读取INI文件的方法。 由于C#本身没有直接操作INI文件的类,我们需要使用Windows API函数。主要用到的两个函数是: - `GetPrivateProfileString`:读取INI文件中的值。 - `WritePrivateProfileString`:向INI文件写入值。 我们将按照以下步骤进行: 1. 导入这两个API函数(使用DllImport)。 2. 封装读取和写入的方法。 注意:INI文件的结构是分节的,每节下有不同的键值对。 下面是一个完整的示例,包括读取和写入INI文件的方法:</think>### C# 读取 INI 文件的方法 在 C#读取 INI 文件需要调用 Windows API 函数,因为 .NET Framework 本身不提供原生支持。以下是完整实现方案: #### 1. 声明 API 函数 ```csharp using System.Runtime.InteropServices; using System.Text; public class IniHelper { [DllImport("kernel32")] private static extern int GetPrivateProfileString( string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernel32")] private static extern long WritePrivateProfileString( string section, string key, string val, string filePath); } ``` #### 2. 读取 INI 值的方法 ```csharp public static string GetValue(string section, string key, string defaultValue, string filePath) { const int bufferSize = 255; var temp = new StringBuilder(bufferSize); int ret = GetPrivateProfileString( section, key, defaultValue, temp, bufferSize, filePath ); return temp.ToString(); } ``` #### 3. 写入 INI 值的方法 ```csharp public static bool SetValue(string section, string key, string value, string filePath) { long result = WritePrivateProfileString(section, key, value, filePath); return result != 0; // 返回操作是否成功 } ``` #### 4. 使用示例 ```csharp // 读取配置 string configFile = @"C:\App\config.ini"; string server = IniHelper.GetValue("Database", "Server", "localhost", configFile); string port = IniHelper.GetValue("Database", "Port", "1433", configFile); // 写入配置 bool success = IniHelper.SetValue("Logging", "Level", "Debug", configFile); ``` #### 注意事项: 1. **文件路径**:需使用物理路径(相对路径或绝对路径) 2. **默认值**:当键不存在时返回预设的默认值 3. **缓冲区大小**:`StringBuilder` 初始化长度决定最大读取长度 4. **字符编码**:API 默认使用系统 ANSI 编码,如需 UTF-8 需额外处理[^1] > 关键原理:通过 `kernel32.dll` 的 `GetPrivateProfileString` API 实现跨进程配置读取,该函数直接解析 INI 文件结构[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值