C#實現(xiàn)讀取ini配置文件的內(nèi)容
一、編寫ini配置文件
ini文件時初始化文件,通常是系統(tǒng)配置文件所采用的存儲格式。ini文件有自己的固定格式,是由若干個“節(jié)”(section)組成,每個節(jié)由若干個“鍵”(key)組成,每個key可以賦值相應(yīng)的“值”(value)。
以下是ini文件的示例,我們將讀取name的值。我這里的項目是窗體應(yīng)用程序。
[section] name=aline age=18
二、效果圖
三、C# 讀取ini文件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region API函數(shù)聲明 [DllImport("kernel32")]//返回取得字符串緩沖區(qū)的長度 private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); #endregion #region 讀Ini文件 public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath) { if (File.Exists(iniFilePath)) { StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath); return temp.ToString(); } else { return String.Empty; } } #endregion // 讀取ini文件 按鈕 private void button1_Click(object sender, EventArgs e) { //配置文件路徑 string iniFilePath = Directory.GetCurrentDirectory() + "\\app.ini"; //MessageBox.Show(iniFilePath); string Section = "section"; string Key = "name"; string NoText = "NoText"; string res = ReadIniData(Section, Key, NoText, iniFilePath); MessageBox.Show(res); } } }
說明:
ReadIniData()是讀取ini文件,四個參數(shù)分別是:①section ini文件里的節(jié)(要和ini文件里的一致);②key 要讀取的鍵(如:name、age);③NoText對應(yīng)API函數(shù)的def參數(shù),它的值由用戶指定,是當在配置文件中沒有找到具體的Value時,就用NoText的值來代替;④iniFilePath ini文件路徑
到此這篇關(guān)于C#實現(xiàn)讀取ini配置文件的內(nèi)容的文章就介紹到這了,更多相關(guān)C#讀取ini配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Winform中Treeview實現(xiàn)按需加載的方法
這篇文章主要介紹了Winform中Treeview實現(xiàn)按需加載的方法,針對大數(shù)據(jù)量的情況下非常具有實用價值,需要的朋友可以參考下2014-10-10C#調(diào)用OpenXml讀取excel行數(shù)據(jù)
這篇文章主要為大家詳細介紹了C#如何調(diào)用OpenXml實現(xiàn)讀取excel行數(shù)據(jù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-12-12