最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#讀寫(xiě)配置文件方式(config.ini)入門(mén)

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

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用法)示例分享

    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#實(shí)現(xiàn)windows form拷貝內(nèi)容到剪貼板的方法,涉及C#操作Clipboard的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • C#中的for和foreach的性能對(duì)比

    C#中的for和foreach的性能對(duì)比

    這篇文章主要介紹了C#中的for和foreach的性能對(duì)比,在C#中,for和foreach是兩種常用的循環(huán)結(jié)構(gòu),用于迭代集合中的元素,盡管它們?cè)诠δ苌舷嗨?但它們?cè)谛阅堋⒖臻g效率和垃圾回收(GC)方面有一些區(qū)別,需要的朋友可以參考下
    2023-10-10
  • C# 判斷字符為空的6種方法的效率實(shí)測(cè)對(duì)比

    C# 判斷字符為空的6種方法的效率實(shí)測(cè)對(duì)比

    本文主要介紹了C#中判斷字符是否為空的方法,并實(shí)測(cè)對(duì)比各種方法的執(zhí)行效率,最后推薦大家使用IsNullOrEmpty,效率和易用性比較均衡。
    2016-05-05
  • VSCode調(diào)試C#程序及附缺失.dll文件的解決辦法

    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#日志存儲(chǔ)優(yōu)化的五種方法

    C#日志存儲(chǔ)優(yōu)化的五種方法

    本文介紹了C#日志存儲(chǔ)優(yōu)化的五種方法,包括日志輪轉(zhuǎn)、壓縮存儲(chǔ)、遠(yuǎn)程存儲(chǔ)、日志級(jí)別控制和日志格式優(yōu)化,通過(guò)合理的配置和優(yōu)化,可以有效避免日志文件無(wú)限增長(zhǎng),節(jié)省磁盤(pán)空間,提高查詢效率和系統(tǒng)性能,需要的朋友可以參考下
    2025-10-10
  • C#生成隨機(jī)ArrayList的方法

    C#生成隨機(jī)ArrayList的方法

    這篇文章主要介紹了C#生成隨機(jī)ArrayList的方法,實(shí)例分析了C#中ArrayList的相關(guān)操作技巧,需要的朋友可以參考下
    2015-06-06
  • C#遞歸讀取XML菜單數(shù)據(jù)的方法

    C#遞歸讀取XML菜單數(shù)據(jù)的方法

    這篇文章主要介紹了C#遞歸讀取XML菜單數(shù)據(jù)的方法,涉及遞歸的操作技巧與C#窗體的用法,對(duì)于進(jìn)行C#項(xiàng)目開(kāi)發(fā)具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2014-12-12
  • C#提高編程能力的50個(gè)要點(diǎn)總結(jié)

    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)代碼

    c#斐波那契數(shù)列(Fibonacci)(遞歸,非遞歸)實(shí)現(xiàn)代碼,需要的朋友可以參考一下
    2013-05-05

最新評(píng)論

宝应县| 安平县| 保山市| 方山县| 青岛市| 敖汉旗| 富锦市| 雅江县| 安义县| 南充市| 象山县| 阿克陶县| 加查县| 富民县| 霞浦县| 江口县| 额敏县| 仲巴县| 张掖市| 七台河市| 华宁县| 连南| 滨州市| 前郭尔| 湘西| 杭锦后旗| 平乡县| 德令哈市| 光山县| 米易县| 永泰县| 广德县| 宝清县| 沐川县| 寿宁县| 华坪县| 鸡西市| 玛纳斯县| 三台县| 贵德县| 罗定市|