ChatGPT解决这个技术问题 Extra ChatGPT

从 .NET 中的 app.config 或 web.config 读取设置

我正在开发一个 C# 类库,它需要能够从 web.configapp.config 文件中读取设置(取决于 DLL 是从 ASP.NET Web 应用程序还是 Windows 窗体应用程序引用的)。

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

有效,但该代码已被 Microsoft 标记为已弃用。

我读过我应该使用:

ConfigurationManager.AppSettings["MySetting"]

但是,C# 类库项目中似乎没有 System.Configuration.ConfigurationManager 类。

做这个的最好方式是什么?

就像我阅读了 4 个 MSDN 示例和文章一样。然后降落在这里。只需添加参考..他们为什么不能这么说。好问题! +1
如果您还想将设置写回,请查看here如何做到这一点。

P
Peter Mortensen

对于如下示例 app.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

您使用下面显示的代码阅读上述应用程序设置:

using System.Configuration;

如果还没有,您可能还需要在项目中添加对 System.Configuration 的引用。然后,您可以像这样访问这些值:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];

我更喜欢你的答案而不是接受的答案。带有示例的答案总是对我有用。
这对我有用。但是,我的 System.Configuration 不包含 ConfigurationManager,因此我必须使用 ConfigurationSettings。具有讽刺意味的是,我仍然收到它已过时的警告。
这也发生在我身上。您是否尝试过添加 System.Configuration 参考?问题是 VS 通过让你认为你真的拥有它来愚弄你。您可以使用智能感知来获取命名空间 System.Configuration 但它没有 ConfigurationManager 类。只需添加参考即可修复它。
@Cricketheads System.Configuration 确实包含 ConfigurationManager,您可能在项目中缺少对 System.Configuration 的引用。
有人能告诉我为什么他们认为 System.Configuration 没有默认添加......这在大多数应用程序中似乎是一个非常基本的需求。
D
DrBeco

您需要在项目的 references 文件夹添加一个引用System.Configuration

您绝对应该使用 ConfigurationManager 而不是过时的 ConfigurationSettings


非常感谢!非常直接的答案。我正在构建一个控制台应用程序!这个答案可以挽救一天!
这对于 .net 核心是否仍然准确。
@Triynko您应该指定您考虑的.NET Core版本以确认兼容性,因为在撰写本文时..您正在查看.NET Core 3.1、.NET 5或6。此外,那些阅读..对于注释,C# 9 和 VS2019 - Program.cs 不需要对 System.Configuration 的引用(不必要)。
P
Peter Mortensen

.NET Framework 4.5 和 4.6 的更新;以下将不再起作用:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

现在通过属性访问设置类:

string keyvalue = Properties.Settings.Default.keyname;

有关详细信息,请参阅 Managing Application Settings


2010 以来的属性。
非常感谢您发布这个。我确定 Properties.Settings.Default.MachName 有效,但我无法弄清楚为什么 ConfigurationManager.AppSettings["MachName"] 返回 null。
这结束了我长期的痛苦。谢谢。该框架应该警告您旧方法已过时。
无法确认。 ConfigurationManager.AppSettings["someKey"] 适用于 .NET 4.5、4.6、4.7.1
@Ivanhoe 你用的是什么版本的 VisualStudio? ConfigurationManager.AppSettings["someKey"] 与 4.6.1 和 VS 15.8.2 一起工作,但对我来说在 4.6.1 和 VS 15.9.2 上失败了。
P
Peter Mortensen

右键单击您的类库,然后从菜单中选择“添加引用”选项。

从 .NET 选项卡中,选择 System.Configuration。这会将 System.Configuration DLL 文件包含到您的项目中。


添加参考后,能够做到ConfigurationManager.ConnectionStrings[0].ConnectionString
P
Peter Mortensen

我正在使用它,它对我很有效:

textBox1.Text = ConfigurationManager.AppSettings["Name"];

TS 明确指出,他使用相同的代码,但他的项目无法编译(由于缺少引用,事实证明)。 -1 表示不阅读问题。
P
Peter Mortensen

从配置中读取:

您需要添加对配置的引用:

在您的项目上打开“属性”转到“设置”选项卡添加“名称”和“值”使用以下代码获取值:字符串值 = Properties.Settings.Default.keyname;

保存到配置:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();

仅供参考:谷歌最喜欢你的回答。当您搜索“get app config settings c#”时逐字显示
P
Peter Mortensen

您必须向项目添加对 System.Configuration 程序集的引用。


P
Peter Mortensen

您可能会将 App.config 文件添加到 DLL 文件中。 App.Config 仅适用于可执行项目,因为所有 DLL 文件都从正在执行的 EXE 文件的配置文件中获取配置。

假设您的解决方案中有两个项目:

一些DLL

一些Exe

您的问题可能与您将 app.config 文件包含到 SomeDLL 而不是 SomeExe 的事实有关。 SomeDll 能够从 SomeExe 项目中读取配置。


哇,这并不明显。如果有人可以链接一个谈论这个的文件,那就太棒了。这是一个很难搜索的话题。
谢谢你。在任何地方都没有看到这说明。
P
Peter Mortensen

尝试这个:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

在 web.config 文件中,这应该是下一个结构:

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>

P
Peter Mortensen

第 1 步:右键单击“参考”选项卡以添加参考。

第 2 步:单击“程序集”选项卡

第 3 步:搜索“System.Configuration”

第四步:点击确定。

然后它将起作用。

 string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];

P
Peter Mortensen

我有同样的问题。以这种方式阅读它们:System.Configuration.ConfigurationSettings.AppSettings["MySetting"]


根据 Microsoft 关于 ConfigurationSettings.AppSettings This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings
此方法已过时
P
Peter Mortensen

web.config 用于网络应用程序。 web.config 默认情况下具有 Web 应用程序所需的多项配置。您可以为 Web 应用程序下的每个文件夹创建一个 web.config

app.config 用于 Windows 应用程序。当您在 Visual Studio 中构建应用程序时,它会自动重命名为 <appname>.exe.config,并且此文件必须与您的应用程序一起交付。

您可以使用相同的方法从两个配置文件中调用 app settings 值:System.Configuration.ConfigurationSettings.AppSettings["Key"]


也可以使用 System.Configuration.COnfigurationSettings.AppSettings.Get("Key") 而不是方括号。
P
Peter Mortensen

正如我找到了以系统方式访问应用程序设置变量的最佳方法,方法是在 System.Configuration 上创建一个包装类,如下所示

public class BaseConfiguration
{
    protected static object GetAppSetting(Type expectedType, string key)
    {
        string value = ConfigurationManager.AppSettings.Get(key);
        try
        {
            if (expectedType == typeof(int))
                return int.Parse(value);
            if (expectedType == typeof(string))
                return value;

            throw new Exception("Type not supported.");
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
                key, expectedType), ex);
        }
    }
}

现在我们可以使用另一个类通过硬编码名称访问所需的设置变量,如下所示:

public class ConfigurationSettings:BaseConfiguration
{
    #region App setting

    public static string ApplicationName
    {
        get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
    }

    public static string MailBccAddress
    {
        get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
    }

    public static string DefaultConnection
    {
        get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
    }

    #endregion App setting

    #region global setting


    #endregion global setting
}

这使用了 OP 指出的方法被标记为已弃用。
P
Peter Mortensen

此外,您可以使用 Formo

配置:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

代码:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();

你到底为什么要这样做?
9年后,它更无关紧要。呸呸呸
C
Chris Catignani

如果您需要/想要使用 ConfigurationManager 类...

您可能需要由 Microsoft 通过 NuGet 包管理器 加载 System.Configuration.ConfigurationManager

工具->NuGet 包管理器->管理解决方案的 NuGet 包...

Microsoft Docs

文档中值得注意的一件事......

如果您的应用程序需要对其自己的配置进行只读访问,我们建议您使用 GetSection(String) 方法。此方法提供对当前应用程序的缓存配置值的访问,比 Configuration 类具有更好的性能。


P
Peter Mortensen

我强烈建议您为此调用创建一个 wrapper。类似于 ConfigurationReaderService 并使用 dependency injection 来获取此类。这样,您将能够隔离此配置文件以进行测试。

所以使用建议的 ConfigurationManager.AppSettings["something"]; 并返回此值。使用此方法,如果 .config 文件中没有任何可用的键,您可以创建某种默认返回。


Microsoft 已经有一种内置方式来管理同一配置文件的多个版本:build configurations,它允许为每个构建配置使用单独的配置文件:app.DEBUG.configapp.RELEASE.configapp.TEST.config 等。
P
Peter Mortensen

为了完整起见,还有一个仅适用于 Web 项目的选项:System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

这样做的好处是它不需要添加额外的引用,因此对于某些人来说可能更可取。


P
Peter Mortensen

我总是使用为所有配置值声明的类型安全属性创建一个 IConfig 接口。 Config 实现类然后包装对 System.Configuration 的调用。您的所有 System.Configuration 调用现在都在一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和清晰。我编写了一组私有辅助方法来读取和解析常见数据类型。

使用 IoC 框架,您只需将接口传递给类构造函数,即可在应用程序中的任何位置访问 IConfig 字段。然后,您还可以在单元测试中创建 IConfig 接口的模拟实现,因此您现在可以测试各种配置值和值组合,而无需修改 App.config 或 Web.config 文件。


P
Peter Mortensen

请检查您正在使用的 .NET 版本。它应该高于 4。并且您必须将 System.Configuration 系统库添加到您的应用程序中。


这个问题是 9 年前提出的,已经有 20 多个答案,其中 2 个每个都有 600 多个赞成票,接受的答案是添加对 System.Configuration 的引用。这个额外的答案不会增加价值。充其量,这应该是对已接受答案的评论。
Re“高于4”:在主版本号?还是您的意思是“高于4.0”?或者换句话说,.NET Framework 4.5 会站在哪一边?
P
Peter Mortensen

您可以使用以下行。就我而言,它正在工作: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

您必须注意上述代码行也是旧版本,并且在新库中已弃用。


P
Peter Mortensen

ConfigurationManager 不是您访问自己的设置所需要的。

为此,您应该使用

{YourAppName}.Properties.Settings.{settingName}


P
Peter Mortensen

我能够使以下方法适用于 .NET Core 项目:

脚步:

在您的项目中创建一个 appsettings.json(格式如下)。接下来创建一个配置类。格式如下。我创建了一个 Login() 方法来显示配置类的用法。在您的项目中创建 appsettings.json 内容:{ "Environments": { "QA": { "Url": "somevalue", "Username": "someuser", "Password": "somepwd" }, "BrowserConfig": { "Browser": "Chrome", "Headless": "true" }, "EnvironmentSelected": { "Environment": "QA" } } public static class Configuration { private static IConfiguration _configuration; static Configuration() { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json"); _configuration = builder.Build(); } 公共静态浏览器 GetBrowser() { if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox") { return Browser.Firefox; } if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge") { return Browser.Edge; } if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE") { return Browser.InternetExplorer; } 返回浏览器.Chrome; } public static bool IsHeadless() { return _configuration.GetSection("BrowserConfig:Headless").Value == "true"; } 公共静态字符串 GetEnvironment() { return _configuration.GetSection("EnvironmentSelected")["Environment"]; } 公共静态 IConfigurationSection EnvironmentInfo() { var env = GetEnvironment(); return _configuration.GetSection($@"Environments:{env}"); } } public void Login() { var environment = Configuration.EnvironmentInfo(); Email.SendKeys(环境["用户名"]); Password.SendKeys(环境["密码"]); WaitForElementToBeClickableAndClick(_driver, SignIn); }


D
Diligent Key Presser

另一种可能的解决方案:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

P
Peter Mortensen

几天来,我一直在尝试解决同样的问题。我能够通过在 web.config 文件的 appsettings 标记中添加一个键来解决此问题。这应该在使用帮助程序时覆盖 .dll 文件。

<configuration>
    <appSettings>
        <add key="loginUrl" value="~/RedirectValue.cshtml" />
        <add key="autoFormsAuthentication" value="false"/>
    </appSettings>
</configuration>

e
esamaldin elzain

extra :如果您正在处理类库项目,则必须嵌入 settings.json 文件。

类库实际上不应该直接引用 app.config 中的任何内容——该类没有 app.config,因为它不是应用程序,而是一个类。

转到 JSON 文件的属性。更改构建操作 -> 嵌入式资源。使用下面的代码来阅读它。

var assembly = Assembly.GetExecutingAssembly();

var resourceStream = assembly.GetManifestResourceStream("Assembly.file.json");

string myString = reader.ReadToEnd();

现在我们有了一个 JSON 字符串,我们可以使用 JsonConvert 对其进行反序列化

如果您没有将文件嵌入程序集中,则不能仅使用没有文件的 DLL 文件


P
Peter Mortensen

这是一个示例:App.config

<applicationSettings>
    <MyApp.My.MySettings>
        <setting name="Printer" serializeAs="String">
            <value>1234 </value>
        </setting>
    </MyApp.My.MySettings>
</applicationSettings>

Dim strPrinterName as string = My.settings.Printer