gpt4 book ai didi

c# - 如何读取 C# app.config 文件中的多个值?

转载 作者:太空狗 更新时间:2023-10-29 22:26:32 25 4
gpt4 key购买 nike

我想读取下面的 app.config 文件。如何读取它?我需要更改任何内容才能读取文件吗??

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Users>
<add username = "Dinesh" password ="Password" domain ="MyCompany" />
<add username = "Kumar" password ="Password" domain ="MyCompany" />
</Users>
</configuration>

最佳答案

我认为你应该实现一个部分。

我制作了一些可能正是您想要的示例代码:

using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace ConsoleApplication1
{
public sealed class UsersConfigMapSection : ConfigurationSection
{
private static UsersConfigMapSection config = ConfigurationManager.GetSection("Users") as UsersConfigMapSection;

public static UsersConfigMapSection Config
{
get
{
return config;
}
}

[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
private UsersConfigMapConfigElements Settings
{
get { return (UsersConfigMapConfigElements)this[""]; }
set { this[""] = value; }
}

public IEnumerable<UsersConfigMapConfigElement> SettingsList
{
get { return this.Settings.Cast<UsersConfigMapConfigElement>(); }
}
}

public sealed class UsersConfigMapConfigElements : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new UsersConfigMapConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((UsersConfigMapConfigElement)element).Username;
}
}

public sealed class UsersConfigMapConfigElement : ConfigurationElement
{
[ConfigurationProperty("username", IsKey = true, IsRequired = true)]
public string Username
{
get { return (string)base["username"]; }
set { base["username"] = value; }
}

[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get { return (string)base["password"]; }
set { base["password"] = value; }
}

[ConfigurationProperty("domain", IsRequired = true)]
public string Domain
{
get { return (string)base["domain"]; }
set { base["domain"] = value; }
}
}
}

然后像这样从配置文件中提取用户:

var users = UsersConfigMapSection.Config.SettingsList.ToList();

最后你的配置文件应该是这样的:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Users" type="ConsoleApplication1.UsersConfigMapSection, ConsoleApplication1"/>
</configSections>
<Users>
<add username = "Dinesh" password ="Password" domain ="MyCompany" />
<add username = "Kumar" password ="Password" domain ="MyCompany" />
</Users>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

关于c# - 如何读取 C# app.config 文件中的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21878374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com