.Net App.Config 讀取

来源:https://www.cnblogs.com/dongyaosheng/archive/2022/12/14/16982434.html
-Advertisement-
Play Games

概述 為什麼要用到深拷貝呢?比如我們建了某個類Person,並且實例化出一個對象,然後,突然需要把這個對象複製一遍,並且複製出來的對象要跟之前的一模一樣,來看下我們一般會怎麼做。 方法一(利用反射實現) public static T DeepCopy<T>(T obj) { //如果是字元串或值類 ...


經常能在.Net 項目中看到App.Config/Web.Config , 一直沒有瞭解過.Net 自帶的對配置文件的讀寫操作,常規的操作類在 System.Configuration.dll 中 ,比較重要的類為ConfigurationManager

底部有全部代碼+單元測試

AppSetting 及 ConnectionString 的讀取

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="MyGroup" type="AppConfig.MyGroup,Appconfig">
      <section name="MySection" type="AppConfig.MySection,Appconfig" />
    </sectionGroup>
    <section name="MySection" type="AppConfig.MySection,Appconfig" />
  </configSections>
  <appSettings>
    <add key="A" value="a"/>
    <add key="B" value="b"/>
    <add key="C" value="c"/>
  </appSettings>
  <connectionStrings>
    <add connectionString="123" name="1"/>
    <add connectionString="456" name="2"/>
  </connectionStrings>
  <MySection Code="asdas">
    <Member Id="dasd"/>
    <Members>
      <add Id="1"/>
      <add Id="2"/>
      <add Id="3"/>
    </Members>
  </MySection>
  <MyGroup>
    <MySection Code="asdas1">
      <Member Id="dasd1"/>
      <Members>
        <add Id="12"/>
        <add Id="22"/>
      </Members>
    </MySection>
  </MyGroup>
</configuration>

指定AppSetting 的 讀取

public string GetAppSettingValue(string appSettingName)
{
    return ConfigurationManager.AppSettings.AllKeys.FirstOrDefault(item => item.Equals(appSettingName)) != null ? ConfigurationManager.AppSettings[appSettingName] : null;
}

指定ConnecString的獲取

public string GetConnectString(string name)
{
    return ConfigurationManager.ConnectionStrings[name]?.ConnectionString;
}

自定義內容的讀取

  • ConfigurationSection
  • ConfigurationElement
  • ConfigurationSectionGroup
  • ConfigurationElementCollection

ConfigurationSection

表示配置文件中的節。

// 自定義一個Section   
internal class MySection : ConfigurationSection
{
    [ConfigurationProperty(nameof(Code))]
    public string Code
    {
        get => base[nameof(Code)].ToString();
    }
}

需要在屬性上使用ConfigurationPropertyAttribute

//調用方法      
public string GetMySectionCode()
{
    return (ConfigurationManager.GetSection("MySection") as MySection)?.Code;
}

ConfigurationElement

表示Section的成員

//根據Config 配置屬性
public class MyElement : ConfigurationElement
{
    [ConfigurationProperty(nameof(Id))]
    public string Id
    {
        get => this[nameof(Id)].ToString();
    }
}
//同時在MySection 中進行擴展
internal class MySection : ConfigurationSection
{
    ...
    [ConfigurationProperty(nameof(Member))]
    public MyElement Member
    {
        get => base[nameof(Member)] as MyElement;
    }
    ...
}
//調用方法
public string GetMySectionMember()
{
    return (ConfigurationManager.GetSection("MySection") as MySection)?.Member?.Id;
}

ConfigurationElementCollection

表示Element的集合

//定義一個MyElement 的集合    
[ConfigurationCollection(typeof(MyElement))]
internal class MyElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return (element as MyElement).Id;
    }
}
//在Section 中進行填充
internal class MySection : ConfigurationSection
{
    [ConfigurationProperty(nameof(Members)), ConfigurationCollection(typeof(MyElement))]
    public MyElementCollection Members
    {
        get => base[nameof(Members)] as MyElementCollection;
    }
}
//調用
public int GetMySectionMembers()
{
    return (int)(ConfigurationManager.GetSection("MySection") as MySection)?.Members?.Count;
}

ConfigurationSectionGroup

在Section 外面在套一個類

public class MyGroup : ConfigurationSectionGroup
{
    [ConfigurationProperty(nameof(MySection))]
    public MySection MySection { get => this.Sections[nameof(MySection)] as MySection; }
}
// 兩種調用方式都可以    
public int GetMySectionMembersInGroup()
{
    return (int)(ConfigurationManager.GetSection("MyGroup/MySection") as MySection)?.Members?.Count;
}
public int GetMySectionMembersInGroupByOpenConfig()
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var group = (MyGroup)config.GetSectionGroup("MyGroup");
    return group.MySection.Members.Count;
}

處理不是預設名字的Config 文件

ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = @".\App1.config" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap,ConfigurationUserLevel.None);

這邊載入方式與上面的不同 後續一致

github


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 什麼是shell? 目前的電腦操作系統都採用了某型形式的用戶界面,藉此指定系統需要操作系統的命令。但是在很多操作系統中,命令行界面是內嵌的,是人與電腦交互的唯一方式。操作系統的命令行頁面就是為了執行您的命令。 shell是一個程式,它的工作就是為了用戶執行其他程式,即系統中允許用戶輸入命令的部分 ...
  • 該篇的IO模型主要針對的是網路IO的,其他IO不在本篇考慮範圍之內! IO模型簡介 Stevens在文章中一共比較了五種IO Model,分別為: * blocking IO 阻塞IO * nonblocking IO 非阻塞IO * IO multiplexing IO多路復用 * signal ...
  • 底層數據結構:動態開闢的數組,每次以原始空間2倍擴容 vector vec; 增加 vec.push_back(100);容器末尾加元素 時間負責度O(1) 可能導致容器擴容 容器中的,對象的構造析構,記憶體的開闢釋放,通過什麼來實現? 容器的空間配置器allocator allocate deall ...
  • 1、什麼是進程、線程、併發、並行 一、進程線程 1、進程 程式由指令和數據組成,但這些指令要運行,數據要讀寫,就必須將指令載入至CPU,數據載入至記憶體。在指令運行過程中還需要用到磁碟、網路等設備。進程就是用來載入指令、管理記憶體、管理IO的當一個程式被運行,從磁碟載入這個程式的代碼至記憶體,這時就開啟了 ...
  • 前言 本文給大家分享的是如何通過利用Python製作藝術簽名生成器,廢話不多直接開整~ 開發工具 Python版本: 3.6 相關模塊: requests模塊 PIL模塊 PyQt5模塊 環境搭建 安裝Python並添加到環境變數,pip安裝需要的相關模塊即可。 文中實戰教程,評論留言獲取。 思路分 ...
  • unique_lock condition_variable 1:lock_guard 和 unique_lock 2:condition_variable wait 和 notify_all 方式1 std::mutex mtx; mtx.lock(); .. ... mtx.unlock();/ ...
  • 2022.12.12 記錄問題方便以後查看。 一、準備工作 1、本次使用jar包啟動後端,故而準備打包後的jar文件。註意修改配置文件中的路徑,根據需要部署的操作系統進行更改。 2、提前寫bat文件用來啟動jar包。 @echo off start "cmd標題名" java -Dfile.enco ...
  • "I don’t care if it works on your machine! We are not shipping your machine!" - Vidiu Platon “我才不管它能不能在你的機器上運行捏!我們又不會給你提供機器!” —— 韋都·柏拉圖 0x00 大綱 0x01 前 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...