C#讀寫(xiě)配置文件方式(config.ini)入門(mén)
C#讀寫(xiě)配置文件(config.ini)
最近學(xué)習(xí)C#,遇到要讀取配置文件的問(wèn)題,記錄下學(xué)習(xí)過(guò)程
代碼部分
namespace 寫(xiě)入讀取配置文件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*
* 1)private 不是必需的,根據(jù)設(shè)計(jì)了,public也可以.
* 2)extern 關(guān)鍵字表示該方法是要調(diào)用非托管代碼.如果使用extern關(guān)鍵字來(lái)引入非托管代碼,則必須也同時(shí)使用static.為什么要用static,是因?yàn)槟阏{(diào)用非托管代碼,總得有個(gè)入口點(diǎn)吧,那么你聲明的這個(gè)GetPrivateProfileString方法就是你要調(diào)用的非托管代碼的入口.想想Main函數(shù),是不是也必須是static呢.
* 3) 為什么要用long,我看也有小伙伴也有用int的,估計(jì)是long支持的更多位數(shù)
*/
[DllImport("kernel32")]// 讀配置文件方法的6個(gè)參數(shù):所在的分區(qū)(section)、 鍵值、 初始缺省值、 StringBuilder、 參數(shù)長(zhǎng)度上限 、配置文件路徑
public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32")]//寫(xiě)入配置文件方法的4個(gè)參數(shù): 所在的分區(qū)(section)、 鍵值、 參數(shù)值、 配置文件路徑
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
/*讀配置文件*/
public static string GetValue(string section, string key)
{
// ▼ 獲取當(dāng)前程序啟動(dòng)目錄
// string strPath = Application.StartupPath + @"/config.ini"; 這里是絕對(duì)路徑
string strPath = "./config.ini"; //這里是相對(duì)路徑
if (File.Exists(strPath)) //檢查是否有配置文件,并且配置文件內(nèi)是否有相關(guān)數(shù)據(jù)。
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "配置文件不存在,讀取未成功!", sb, 255, strPath);
return sb.ToString();
}
else
{
return string.Empty;
}
}
/*寫(xiě)配置文件*/
public static void SetValue(string section, string key, string value)
{
// ▼ 獲取當(dāng)前程序啟動(dòng)目錄
// string strPath = Application.StartupPath + @"/config.ini"; 這里是絕對(duì)路徑
string strPath = "./config.ini"; //這里是相對(duì)路徑,
WritePrivateProfileString(section, key, value, strPath);
}
private void button1_Click_1(object sender, EventArgs e)
{
richTextBox1.Text = GetValue("參數(shù)", "波特率"); //這里通過(guò)界面的按鈕,讀取配置文件。
}
private void richTextBox1_TextChanged(object sender, EventArgs e)//當(dāng)winform界面的數(shù)據(jù)更改時(shí),自動(dòng)保存到配置文件,以便下次打開(kāi)時(shí)保持最后更改的數(shù)據(jù)
{
SetValue("參數(shù)", "波特率",this.richTextBox1.Text.ToString());
}
private void Form1_Load(object sender, EventArgs e)//程序開(kāi)始自動(dòng)讀取上一次配置后的文件
{
richTextBox1.Text = GetValue("參數(shù)", "波特率"); //這里通過(guò)界面的按鈕,讀取配置文件。
}
}
}配置文件(config.ini) 部分

winform部分
第一次啟動(dòng)如下圖所示,點(diǎn)擊按鈕沒(méi)有任何數(shù)據(jù),需要先寫(xiě)入,如10,程序自動(dòng)將10存入配置文件中。
關(guān)閉程序,再打開(kāi),文本框就有10了。

C#使用App.config和INI兩種方式讀寫(xiě)配置文件
說(shuō)明
將系統(tǒng)參數(shù)寫(xiě)到配置文件中,可避免修改參數(shù)必須重新打包程序問(wèn)題。
c#操作配置文件有幾種方法,下面分別介紹使用App.config和INI文件方式管理。
使用App.config
注意:
- 程序編譯后App.config會(huì)編譯為“項(xiàng)目名.exe.config”文件。
- 程序中需要添加引用System.Configuration。
- App.config可讀寫(xiě)數(shù)據(jù)庫(kù)連接參數(shù)和用戶自定義參數(shù)。
- 讀配置信息
App.config文件
<connectionStrings> ?? ?<add name="dbConnectionString" connectionString="Data Source=10.0.1.11;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=xxx;Max Pool Size=512" providerName="System.Data.SqlClient"/> </connectionStrings> <appSettings> ?? ?<add key="abc" value="welcome"/> </appSettings>
讀數(shù)據(jù)庫(kù)配置信息
SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
讀自定義信息
String str = ConfigurationManager.AppSettings["abc"];
- 寫(xiě)配置信息
寫(xiě)配置信息要用到OpenExeConfiguration。
//獲取可操作的Configuration對(duì)象
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
?//寫(xiě)入<add>元素的Value
?config.AppSettings.Settings["abc"].Value = "hello";
?//保存
?config.Save();
?//刷新
?ConfigurationManager.RefreshSection("appSettings");使用INI文件
優(yōu)點(diǎn)為配置文件可以指定路徑,配置信息格式簡(jiǎn)單,使用系統(tǒng)庫(kù)文件即可操作ini文件。
- 系統(tǒng)方法類
public class IniService
? ? {
? ? ? //引入系統(tǒng)庫(kù)文件
? ? ? [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);
? ? ? [DllImport("kernel32.dll")]
? ? ? private extern static int WritePrivateProfileSectionA(string segName, string sValue, string fileName);
public string iniPath;
? ? ? /// <summary>
? ? ? /// 構(gòu)造方法
? ? ? /// </summary>
? ? ? /// <param name="INIPath">文件路徑</param>
? ? ? public IniService(string INIPath)
? ? ? {
? ? ? ? ? iniPath = INIPath;
? ? ? }
? ? ? /// <summary>
? ? ? /// 寫(xiě)入INI文件
? ? ? /// </summary>
? ? ? /// <param name="Section">項(xiàng)目名稱(如 [TypeName] )</param>
? ? ? /// <param name="Key">鍵</param>
? ? ? /// <param name="Value">值</param>
? ? ? public void IniWriteValue(string Section, string Key, string Value)
? ? ? {
? ? ? ? ? WritePrivateProfileString(Section, Key, Value, this.iniPath);
? ? ? }
? ? ? /// <summary>
? ? ? /// 讀出INI文件
? ? ? /// </summary>
? ? ? /// <param name="Section">項(xiàng)目名稱(如 [TypeName] )</param>
? ? ? /// <param name="Key">鍵</param>
? ? ? public string IniReadValue(string Section, string Key)
? ? ? {
? ? ? ? ? StringBuilder temp = new StringBuilder(500);
? ? ? ? ? int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.iniPath);
? ? ? ? ? return temp.ToString();
? ? ? }
? ? ? /// <summary>
? ? ? /// 刪除指定的節(jié)的所有內(nèi)容
? ? ? /// </summary>
? ? ? /// <param name="Section">要?jiǎng)h除的節(jié)的名字</param>
? ? ? public void DeleteSection(string Section)
? ? ? {
? ? ? ? ? WritePrivateProfileSectionA(Section, null, this.iniPath);
? ? ? }
? ? ? /// <summary>
? ? ? /// 驗(yàn)證文件是否存在
? ? ? /// </summary>
? ? ? /// <returns>布爾值</returns>
? ? ? public bool isExistINIFile()
? ? ? {
? ? ? ? ? return File.Exists(iniPath);
? ? ? }
? }- 測(cè)試
使用時(shí)需要指定ini文件位置,測(cè)試程序在工程中新建config文件夾,創(chuàng)建System.ini文件,并且右鍵屬性中設(shè)置“如果較新則復(fù)制”。
?? ??? ??? ?//獲取程序路徑
? ? ? ? ? ? string stCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
? ? ? ? ? ? if (!stCurrentPath.Substring(stCurrentPath.Length - 1).Equals(@"\"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? stCurrentPath = stCurrentPath + @"\";
? ? ? ? ? ? }
? ? ? ? ? ? //初始化IniService
? ? ? ? ? ?IniService ini = new IniService(stCurrentPath + "config\\System.ini");
? ? ? ? ? ?//寫(xiě)入System.ini
?? ??? ??? ?ini.IniWriteValue("Sys", "Msg","Welcome");
?? ??? ??? ?//讀數(shù)據(jù)
? ? ? ? ? ? string strInterval = ini.IniReadValue("Sys", "Msg");配置文件
System.ini
[Sys]
Msg=Welcome
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#在后臺(tái)運(yùn)行操作(BackgroundWorker用法)示例分享
BackgroundWorker類允許在單獨(dú)的專用線程上運(yùn)行操作。如果需要能進(jìn)行響應(yīng)的用戶界面,而且面臨與這類操作相關(guān)的長(zhǎng)時(shí)間延遲,則可以使用BackgroundWorker類方便地解決問(wèn)題,下面看示例2013-12-12
C#實(shí)現(xiàn)windows form拷貝內(nèi)容到剪貼板的方法
這篇文章主要介紹了C#實(shí)現(xiàn)windows form拷貝內(nèi)容到剪貼板的方法,涉及C#操作Clipboard的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C# 判斷字符為空的6種方法的效率實(shí)測(cè)對(duì)比
本文主要介紹了C#中判斷字符是否為空的方法,并實(shí)測(cè)對(duì)比各種方法的執(zhí)行效率,最后推薦大家使用IsNullOrEmpty,效率和易用性比較均衡。2016-05-05
VSCode調(diào)試C#程序及附缺失.dll文件的解決辦法
這篇文章主要介紹了VSCode調(diào)試C#程序及附缺失.dll文件的解決辦法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
C#提高編程能力的50個(gè)要點(diǎn)總結(jié)
這篇文章主要介紹了C#提高編程能力的50個(gè)要點(diǎn),較為詳細(xì)的總結(jié)分析了C#程序設(shè)計(jì)中常見(jiàn)的注意事項(xiàng)與編程技巧,需要的朋友可以參考下2016-02-02
c#斐波那契數(shù)列(Fibonacci)(遞歸,非遞歸)實(shí)現(xiàn)代碼
c#斐波那契數(shù)列(Fibonacci)(遞歸,非遞歸)實(shí)現(xiàn)代碼,需要的朋友可以參考一下2013-05-05

