在C# WinForm應用程序中,INI文件常被用作簡單的配置文件,用于存儲應用程序的設置和參數。INI文件是一種文本文件,其結構通常包括節(Sections)和鍵值對(Key-Value Pairs)。每個節都包含一個或多個鍵值對,用于存儲相關的配置信息。
本文將介紹如何在C# WinForm程序中讀取和寫入INI配置文件,包括創建INI文件、讀取INI文件中的數據以及向INI文件中寫入數據。
INI文件的基本結構非常簡單,由節(Sections)和鍵值對(Key-Value Pairs)組成。每個節由方括號包圍,例如[SectionName],而鍵值對則是以等號=分隔的字符串,例如Key=Value。下面是一個簡單的INI文件示例:
[AppSettings]Setting1=Value1Setting2=Value2[Database]Server=localhostPort=3306
在這個示例中,有兩個節:AppSettings和Database。每個節下都有一些鍵值對,用于存儲配置信息。
在C#中,可以使用System.Configuration命名空間下的IniFile類或者System.IO命名空間下的文件操作方法來讀取INI文件中的數據。這里我們使用System.IO的方法來實現。
using System;using System.IO;using System.Text;using System.Collections.Generic;public class IniFileReader{ private string filePath; public IniFileReader(string filePath) { this.filePath = filePath; } public string ReadValue(string section, string key) { string value = string.Empty; if (File.Exists(filePath)) { var lines = File.ReadAllLines(filePath, Encoding.Default); foreach (var line in lines) { var trimmedLine = line.Trim(); if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]")) { var currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2); if (currentSection == section) { var keyValue = line.Split('='); if (keyValue.Length == 2 && keyValue[0].Trim() == key) { value = keyValue[1].Trim(); break; } } } } } return value; }}
使用上述IniFileReader類,你可以像下面這樣讀取INI文件中的數據:
var reader = new IniFileReader("path_to_your_file.ini");string setting1Value = reader.ReadValue("AppSettings", "Setting1");Console.WriteLine(setting1Value); // 輸出: Value1
向INI文件中寫入數據同樣可以使用System.IO命名空間下的文件操作方法來實現。下面是一個簡單的示例:
using System;using System.IO;using System.Text;public class IniFileWriter{ private string filePath; public IniFileWriter(string filePath) { this.filePath = filePath; } public void WriteValue(string section, string key, string value) { var lines = new List<string>(); bool isSectionFound = false; if (File.Exists(filePath)) { lines = File.ReadAllLines(filePath, Encoding.Default).ToList(); } foreach (var line in lines) { var trimmedLine = line.Trim(); if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]")) { var currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2); if (currentSection == section) { isSectionFound = true; var keyValueLine = $"{key}={value}"; int index = lines.IndexOf(line); lines.Insert(index + 1, keyValueLine); break; } } } if (!isSectionFound) { lines.Add($"[{section}]"); lines.Add($"{key}={value}"); } File.WriteAllLines(filePath, lines, Encoding.Default
本文鏈接:http://www.www897cc.com/showinfo-26-77682-0.htmlC# WinForm程序中讀寫INI配置文件的技術詳解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: Vue3問題:如何在頁面上添加水印?
下一篇: GaussDB WDR分析之集群報告篇