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

问题描述 投票:713回答:22

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

我发现了

ConfigurationSettings.AppSettings.Get("MySetting")

但是该代码已被Microsoft标记为已弃用。

我读过我应该使用的:

ConfigurationManager.AppSettings["MySetting"]

但是,System.Configuration.ConfigurationManager类似乎不能从C#类库项目中获得。

有谁知道最好的方法是什么?

c# .net configuration appsettings
22个回答
747
投票

您需要在项目的references文件夹中添加对System.Configuration的引用。

你肯定应该使用ConfigurationManager而不是过时的ConfigurationSettings


8
投票

我有同样的问题,只需这样阅读:

web.config

7
投票

web.config与Web应用程序一起使用。默认情况下,web.config具有Web应用程序所需的多个配置。您可以为Web应用程序下的每个文件夹添加app.config

<appname>.exe.config用于Windows应用程序。在vs.net中构建应用程序时,它将自动重命名为app settings,此文件必须与您的应用程序一起提供。

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

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);
            }
        }
    }

5
投票

我通过在System.Configuration上创建一个包装类来找到以系统方式访问app设置变量的最佳方法,如下所示

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
    }

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

ConfigurationReaderService

4
投票

我强烈建议您为此调用创建一个包装器。像ConfigurationManager.AppSettings["something"];之类的东西,并使用依赖注入来获得这个类。这样,您就可以隔离此配置文件以进行测试。

因此,使用建议的formo并返回此值。如果.config文件中没有可用的密钥,您可以使用此方法创建某种默认返回。


4
投票

此外,您可以使用<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>();

码:

System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

3
投票

为了完整起见,还有另一个选项可用于Web项目:

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

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


2
投票

我总是创建一个IConfig接口,其中包含为所有配置值声明的类型安全属性。然后,Config实现类将调用包装到System.Configuration。现在,您所有的System.Configuration调用都在一个地方,以便更轻松,更清晰地维护和跟踪正在使用的字段并声明其默认值。我编写了一组私有帮助器方法来读取和解析常见的数据类型。

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


2
投票

步骤1:右键单击引用选项卡以添加引用。

第2步:单击“装配”选项卡

第3步:搜索“System.Configuration”

第4步:单击“确定”。

然后它会工作

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

1
投票

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

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

1
投票

另一种可能的方案

System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

797
投票

对于Sample 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"]; 的引用。然后,您可以像这样访问值:

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

希望这可以帮助!


1
投票

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


1
投票

你可以使用下面的行,在我的情况下它工作:

{YourAppName}.Properties.Settings.{settingName}

你必须注意上面的代码行也是旧版本,并且在新库中不推荐使用它。


1
投票

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

要做到这一点,你应该使用

**For .netcore projects** Create appsettings.json in your project with content : ` { "Environments": { "QA": { "Url": "somevalue", "Username": "someuser", "Password": "somepwd" }, "BrowserConfig": { "Browser": "Chrome", "Headless": "true" }, "EnvironmentSelected": { "Environment": "QA" } } ` Create a Configuration class contents: ` public static class Configuration { private static IConfiguration _configuration; static Configuration() { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json"); _configuration = builder.Build(); } public static Browser 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; } return Browser.Chrome; } public static bool IsHeadless() { return _configuration.GetSection("BrowserConfig:Headless").Value == "true"; } public static string GetEnvironment() { return _configuration.GetSection("EnvironmentSelected")["Environment"]; } public static IConfigurationSection EnvironmentInfo() { var env = GetEnvironment(); return _configuration.GetSection($@"Environments:{env}"); } } ` Usage : ` public void Login() { var environment = Configuration.EnvironmentInfo(); Email.SendKeys(environment["username"]); Password.SendKeys(environment["password"]); WaitForElementToBeClickableAndClick(_driver, SignIn); } `


0
投票
App.config

-1
投票

制作控制台应用程序时遇到了类似的问题。使用Visual Studios,我使用.Net Core而不是.Net Framework。将代码切换到.Net Framework后,我可以访问属性选项卡中的设置。希望这有助于某人!


-4
投票

这是一个例子:<applicationSettings> <MyApp.My.MySettings> <setting name="Printer" serializeAs="String"> <value>1234 </value> </setting> </MyApp.My.MySettings> </applicationSettings> Dim strPrinterName as string= My.settings.Printer

qazxswpoi

71
投票

框架4.5和4.6的更新;以下将不再有效:

string keyvalue= Properties.Settings.Default.keyname;

现在通过Properties访问Setting类:

Managing Application Settings

有关更多信息,请参阅textBox1.Text = ConfigurationManager.AppSettings["Name"];


36
投票

右键单击您的类库,然后从菜单中选择“添加引用”选项;最后从.NET选项卡中选择System.Configuration。这将包括System.Configuration dll到您的项目中。


29
投票

我使用这个,它适合我

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

22
投票

从配置中读取:

您需要添加对Config的引用

  1. 在项目中打开“属性”
  2. 转到“设置”标签
  3. 添加“名称”和“值”
  4. 使用以下代码获取价值: string value = Properties.Settings.Default.keyname;

保存到配置:

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

21
投票

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


17
投票

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

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

  • SomeDll
  • SomeExe

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


9
投票

试试这个:

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

在web.config中应该是下一个结构:

System.Configuration.ConfigurationSettings.AppSettings["MySetting"]
© www.soinside.com 2019 - 2024. All rights reserved.