欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#讀寫配置文件方式(config.ini)入門

 更新時(shí)間:2023年06月16日 15:50:09   作者:kidylong  
這篇文章主要介紹了C#讀寫配置文件方式(config.ini)入門,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

C#讀寫配置文件(config.ini)

最近學(xué)習(xí)C#,遇到要讀取配置文件的問題,記錄下學(xué)習(xí)過程

代碼部分

namespace 寫入讀取配置文件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /*
         * 1)private 不是必需的,根據(jù)設(shè)計(jì)了,public也可以.
         * 2)extern 關(guān)鍵字表示該方法是要調(diào)用非托管代碼.如果使用extern關(guān)鍵字來引入非托管代碼,則必須也同時(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ù)長度上限 、配置文件路徑
        public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
        [DllImport("kernel32")]//寫入配置文件方法的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"; 這里是絕對路徑
            string strPath = "./config.ini";  //這里是相對路徑
            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;
            }
        }
        /*寫配置文件*/
        public static void SetValue(string section, string key, string value)
        {
            // ▼ 獲取當(dāng)前程序啟動(dòng)目錄
           // string strPath = Application.StartupPath + @"/config.ini";  這里是絕對路徑
            string strPath = "./config.ini";      //這里是相對路徑,
            WritePrivateProfileString(section, key, value, strPath);
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            richTextBox1.Text = GetValue("參數(shù)", "波特率");  //這里通過界面的按鈕,讀取配置文件。
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)//當(dāng)winform界面的數(shù)據(jù)更改時(shí),自動(dòng)保存到配置文件,以便下次打開時(shí)保持最后更改的數(shù)據(jù)
        {
           SetValue("參數(shù)", "波特率",this.richTextBox1.Text.ToString());      
        }
         private void Form1_Load(object sender, EventArgs e)//程序開始自動(dòng)讀取上一次配置后的文件
        {
            richTextBox1.Text = GetValue("參數(shù)", "波特率");  //這里通過界面的按鈕,讀取配置文件。
        }
    }
}

配置文件(config.ini) 部分

winform部分

第一次啟動(dòng)如下圖所示,點(diǎn)擊按鈕沒有任何數(shù)據(jù),需要先寫入,如10,程序自動(dòng)將10存入配置文件中。

關(guān)閉程序,再打開,文本框就有10了。

C#使用App.config和INI兩種方式讀寫配置文件

說明

將系統(tǒng)參數(shù)寫到配置文件中,可避免修改參數(shù)必須重新打包程序問題。

c#操作配置文件有幾種方法,下面分別介紹使用App.config和INI文件方式管理。

使用App.config

注意:

  • 程序編譯后App.config會(huì)編譯為“項(xiàng)目名.exe.config”文件。
  • 程序中需要添加引用System.Configuration。
  • App.config可讀寫數(shù)據(jù)庫連接參數(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ù)庫配置信息

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;

讀自定義信息

String str = ConfigurationManager.AppSettings["abc"];
  • 寫配置信息

寫配置信息要用到OpenExeConfiguration。

//獲取可操作的Configuration對象
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
?//寫入<add>元素的Value
?config.AppSettings.Settings["abc"].Value = "hello";
?//保存
?config.Save();
?//刷新
?ConfigurationManager.RefreshSection("appSettings");

使用INI文件

優(yōu)點(diǎn)為配置文件可以指定路徑,配置信息格式簡單,使用系統(tǒng)庫文件即可操作ini文件。

  • 系統(tǒng)方法類
public class IniService
? ? {
? ? ? //引入系統(tǒng)庫文件
? ? ? [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>
? ? ? /// 寫入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);
? ? ? }
? }
  • 測試

使用時(shí)需要指定ini文件位置,測試程序在工程中新建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");
? ? ? ? ? ?//寫入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# winform主界面打開并關(guān)閉登錄界面的方法

    C# winform主界面打開并關(guān)閉登錄界面的方法

    這篇文章主要介紹了C# winform主界面打開并關(guān)閉登錄界面的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • c#文件下載示例的4種方法分享

    c#文件下載示例的4種方法分享

    這篇文章主要介紹了c#文件下載示例的4種方法,有TransmitFile實(shí)現(xiàn)下載,WriteFile實(shí)現(xiàn)下載,WriteFile分塊下載,流方式下載,需要的朋友可以參考下
    2014-03-03
  • c# 中文轉(zhuǎn)拼音without CJK

    c# 中文轉(zhuǎn)拼音without CJK

    本文主要介紹了中文轉(zhuǎn)拼音without CJK,文章篇尾附上源碼下載。具有一定的參考價(jià)值,下面跟著小編一起來看下吧
    2017-02-02
  • 學(xué)習(xí)Winform分組類控件(Panel、groupBox、TabControl)

    學(xué)習(xí)Winform分組類控件(Panel、groupBox、TabControl)

    這篇文章主要和大家一起學(xué)習(xí)Winform分組類控件,包括容器控件(Panel),分組框控件(groupBox)和選項(xiàng)卡控件(TabControl)等控件,感興趣的小伙伴們可以參考一下
    2016-05-05
  • C#中數(shù)組、ArrayList和List三者的區(qū)別詳解及實(shí)例

    C#中數(shù)組、ArrayList和List三者的區(qū)別詳解及實(shí)例

    這篇文章主要介紹了C#中數(shù)組、ArrayList和List三者的區(qū)別詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2016-12-12
  • 最新評論