簡體   English   中英

循環通過 App.Config 文件並將每個值存儲在 C# 控制台應用程序的變量中?

[英]Loop Through App.Config file and store each value in variable for C# Console Application?

這是我的 app.config 文件的結構。

<configuration> 
  <IspacDeployConfig>    
    <appSettings> <!-- ISPAC File 1 -->      
      <add key="DestinationProjectFolderPath" value="/SSISDB/Training/Staging" />
      <add key="IspacFilePath" value="C:\ISPAC\Staging.ispac" />
    </appSettings>
    <appSettings> <!-- ISPAC File 2 -->
      <add key="DestinationProjectFolderPath" value="/SSISDB/Training/DataMart" />
      <add key="IspacFilePath" value="C:\ISPAC\DataMart.ispac" />
    </appSettings>    
  </IspacDeployConfig>
</configuration>


我想循環並獲取變量中的 DestinationProjectFolderPath 和 IspacFilePath 值以進行進一步處理。 有沒有辦法在不使用 Custom.config 文件的情況下做到這一點。 到目前為止,我曾經做過以下操作,但不確定如何遍歷上述文件。

ConfigurationManager.AppSettings.Get

循環通過 xml 文件並將它們存儲在變量中以供重用。

string DestinationPath = DestinationProjectFolderPath ;                
string ProjectFilePath = IspacFilePath ;

您可以使用以下邏輯從配置中獲取所有鍵並將它們添加到字典中。 如果您的配置有多個 appSettings 標簽,此代碼將不起作用

注意:請添加所需的命名空間和對項目的引用。

var appKeys = ((NameValueCollection)ConfigurationManager.AppSettings).AllKeys;
Dictionary<string, string> allKeys = new Dictionary<string, string>();
foreach (var appKey in appKeys)
{
   if(!allKeys.ContainsKey(appKey))
       allKeys.Add(appKey, ConfigurationManager.AppSettings[appKey])
}

首先創建自定義 class

 public class CustomConfig
    {
        private static List< Dictionary<string, string>> keyValuePairs = new List<Dictionary<string, string>>();

        public CustomConfig()
        {
            var xml = XDocument.Load(System.Reflection.Assembly.GetEntryAssembly().Location + ".config");


            var query = from c in xml.Root.Descendants("appSettings")
                        select c;

            foreach (var apps in query)
            {
                var addkeys = apps.Descendants("add");
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (var item in addkeys)
                {
                    dic.Add(item.FirstAttribute.Value, item.LastAttribute.Value);

                }
                keyValuePairs.Add(dic);
            }
        }
      
        public Dictionary<string, string> this [int index]
        {
            get
            {
               return keyValuePairs[index];
            }
        }

    }

然后在 Main 方法中使用以下代碼訪問成員:

string DestinationProjectFolderPath1 = new CustomConfig()[0]["DestinationProjectFolderPath"];
            string DestinationProjectFolderPath2 = new CustomConfig()[1]["DestinationProjectFolderPath"];

            string IspacFilePath1 = new CustomConfig()[0]["IspacFilePath"];
            string IspacFilePath2 = new CustomConfig()[1]["IspacFilePath"];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM