[英]Loop Through App.Config file and store each value in variable for C# Console Application?
This is structure of my app.config file.这是我的 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>
I want to loop through and Fetch DestinationProjectFolderPath & IspacFilePath value in variable for further processing.我想循环并获取变量中的 DestinationProjectFolderPath 和 IspacFilePath 值以进行进一步处理。 Is there any way to do this without using Custom.config file.有没有办法在不使用 Custom.config 文件的情况下做到这一点。 So far I used to do following but not sure how do loop through above file.到目前为止,我曾经做过以下操作,但不确定如何遍历上述文件。
ConfigurationManager.AppSettings.Get
Loop through xml file and store them in variable for reuse.循环通过 xml 文件并将它们存储在变量中以供重用。
string DestinationPath = DestinationProjectFolderPath ;
string ProjectFilePath = IspacFilePath ;
You can use the below logic to get all the keys from config and add them to a Dictionary.您可以使用以下逻辑从配置中获取所有键并将它们添加到字典中。 This code will not work if your config has multiple appSettings tags如果您的配置有多个 appSettings 标签,此代码将不起作用
Note: Please add the required namespace and reference to the project.注意:请添加所需的命名空间和对项目的引用。
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])
}
First create the custom class首先创建自定义 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];
}
}
}
Then in the Main method access members using below code:然后在 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.