C#读写INI文件

  虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。
  INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value):
  [Section]  Key=Value
  VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。

INIFILE类:
using System;
using System.IO;
using System.Runtime.InteropServices;
因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

using System.Text;
namespace Ini{
    public class IniFile
    {
        public string path;    //INI文件名
        [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);        //声明读写INI文件的API函数
        public IniFile(string INIPath)
        {
            path = INIPath;
        }        //类的构造函数,传递INI文件名
        publicvoid IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }        //写INI文件
        publicstring IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);
            return temp.ToString();
        }        //读取INI文件指定
    }
}
调用INIFILE类:

新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。

增加如下代码:
using Ini;  //创建命名空间//当窗体关闭时保存窗体坐标
privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
 IniFile ini = new IniFile("C://test.ini");
 ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString());
 ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString()); //ToString方法将数字转换为字符串}//当窗体启动时,读取INI文件的值并赋值给窗体
privatevoid Form1_Load(object sender, System.EventArgs e)
{
 IniFile ini = new IniFile("C://test.ini");
 Point p=new Point(); //判断返回值,避免第一次运行时为空出错
 if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))
 {
  p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));
  p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));  // int.Parse将字符串转换为int    this.Location =p;
 }

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"); ... ``` 然后逐行分析存储的数据并将其转换回字典形式等更易访问的形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值