C#读写INI文件

本文提供了一个C#读写INI文件的示例代码,详细展示了如何使用GetPrivateProfileInt和WritePrivateProfileString等函数进行读写操作。这些函数用于保存和恢复程序的用户设置,如窗口大小和位置,以防止因系统设置问题导致的错误。

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

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

namespace ReadWriteINI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileInt(
           string lpApplicationName,
           string lpKeyName,
           int nDefault,
           string lpFileName);
        [DllImport("kernel32")]
        private static extern bool GetPrivateProfileString(
          string lpApplicationName,
          string lpKeyName,
          string lpDefault,
          StringBuilder lpReturnedString,
          int nSize,
          string lpFileName);
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(
          string lpApplicationName,
          string lpKeyName,
          string lpString,
          string lpFileName);

        [DllImport("kernel32")]
        private static extern bool GetPrivateProfileSection(
          string lpAppName,
          StringBuilder lpReturnedString,
          int nSize,
          string lpFileName);
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileSection(
          string lpAppName,
          string lpString,
          string lpFileName);

        public static string FILE_NAME;

        private void Form1_Load(object sender, EventArgs e)
        {
            FILE_NAME = Application.StartupPath + "//test.ini";
            if (File.Exists(FILE_NAME))
            {
                StringBuilder strCaption = new StringBuilder(256);
                GetPrivateProfileString("Form", "Caption", "Default Caption",
                 strCaption,
                 strCaption.Capacity,
                 FILE_NAME);
                this.Text = strCaption.ToString();

                int myWidth = GetPrivateProfileInt("Form", "Width", this.Width, FILE_NAME);
                this.Width = myWidth;

                int myHeight = GetPrivateProfileInt("Form", "Height", this.Height, FILE_NAME);
                this.Height = myHeight;

                int myLeft = GetPrivateProfileInt("Form", "Left", this.Left, FILE_NAME);
                this.Left = myLeft;

                int myTop = GetPrivateProfileInt("Form", "Top", this.Top, FILE_NAME);

                this.Top = myTop;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strCaption = this.Text;
            WritePrivateProfileString("Form", "Caption", strCaption, FILE_NAME);
            WritePrivateProfileString("Form", "Width", this.Width.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Hight", this.Height.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Left", this.Left.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Top", this.Top.ToString(), FILE_NAME);

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string strCaption = this.Text;
            WritePrivateProfileString("Form", "Caption", strCaption, FILE_NAME);
            WritePrivateProfileString("Form", "Width", this.Width.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Hight", this.Height.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Left", this.Left.ToString(), FILE_NAME);
            WritePrivateProfileString("Form", "Top", this.Top.ToString(), FILE_NAME);

        }

  }

 

上面是C#中读写INI文件的一个范例代码,关键函数是在类定义那一段,那些函数仅作为声明,无需用户定义,它们也是固定的,可以满足基本的INI读写操作。

INI设置可以保存用户对于程序设置的修改等,可以防止系统设置出现空白而导致的错误。

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、付费专栏及课程。

余额充值