从app.config或web上读取设置。在。net配置

时间:2022-07-05 23:12:54

I'm working on a C# class library that needs to be able to read settings from the web.config or app.config file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).

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

I've found that

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by Microsoft.

可以,但是该代码已经被微软标记为不赞成。

I've read that I should be using:

我读到过,我应该使用:

ConfigurationManager.AppSettings["MySetting"]

However, the System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.

然而,System.Configuration。配置管理器类似乎不能从c#类库项目中获得。

Does anyone know what the best way to do this is?

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

19 个解决方案

#1


641  

You'll need to add a reference to System.Configuration in your project's references folder.

您需要向系统添加一个引用。项目引用文件夹中的配置。

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.

您应该使用ConfigurationManager,而不是过时的ConfigurationSettings。

#2


660  

For Sample App.config like below:

以下是示例App.config:

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

You read the above app settings using code shown below:

您使用如下代码阅读上述应用程序设置:

using System.Configuration;

You may also need to also add a reference to System.Configuration in your project if there isn't one already. You can then access the values like so:

您可能还需要向系统添加一个引用。如果项目中还没有配置的话。然后您可以访问这样的值:

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

Hope this helps!

希望这可以帮助!

#3


51  

Update for framework 4.5 and 4.6; the following will no longer work:

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

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

Now access the Setting class via Properties:

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

string keyvalue= Properties.Settings.Default.keyname;

See Managing Application Settings for more information.

有关更多信息,请参见管理应用程序设置。

#4


34  

Right click on your class Library, and choose the "Add References" option from the Menu; and finally from the .NET tab, select System.Configuration. This would include System.Configuration dll into your project.

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

#5


27  

Im using this and it works well for me

我用这个,它对我很有效

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

#6


18  

You must add to the project a reference to the System.Configuration assembly.

您必须向项目添加对系统的引用。配置组装。

#7


12  

You might be adding the App.config file to a DLL. App.Config works only for executable projects, since all the dll take the configuration from the configuration file for the exe being executed.

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

Let's say you have two projects in your solution:

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

  • SomeDll
  • SomeDll
  • SomeExe
  • SomeExe

Your problem might be releated to the fact that you're including the app.config to SomeDLL and not SomeExe. SomeDll is able to read the configuration from the SomeExe project.

您的问题可能与您将app.config包含到某个dll而不是SomeExe有关。SomeDll可以从SomeExe项目中读取配置。

#8


10  

Read From Config :

读取配置:

You'll need to add a reference to Config

您需要向Config添加一个引用

  1. Open "Properties" on your project
  2. 在项目中打开“属性”
  3. Go to "Settings" Tab
  4. 进入“设置”选项卡
  5. Add "Name" and "Value"
  6. 添加“Name”和“价值”
  7. Get Value with using following code :

    使用以下代码获取值:

    string value = Properties.Settings.Default.keyname;

    字符串值= Properties.Settings.Default.keyname;

Save to Config :

保存到配置:

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

#9


5  

I had the same problem, just read them this way:

我也有同样的问题,就这样读:

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

#10


5  

Try this:

试试这个:

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

In web.config should be next structure:

在网络上。配置应该是下一个结构:

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

#11


4  

web.config is used with web applications.web.config will by default have several configurations required for the web application. You can have a web.config for each folder under your web application.

网络。配置用于web application .web。默认情况下,配置将具有web应用程序所需的多个配置。你可以有一个网络。为web应用程序下的每个文件夹配置。

app.config is used for windows applications. When you build the application in vs.net, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.

config用于windows应用程序。当您在vs.net中构建应用程序时,它将被自动重命名为 .exe。配置文件和这个文件必须与您的应用程序一起交付。

You can use the same method to call the app settings values from both config files :

您可以使用相同的方法从两个配置文件调用app设置值:

System.Configuration.COnfigurationSettings.AppSettings["Key"]

#12


2  

I strongly recommend you to create a Wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

我强烈建议您为这个调用创建一个包装器。类似于ConfigurationReaderService和使用依赖注入来获得这个类。通过这种方式,您将能够为测试目的隔离这个配置文件。

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.

所以使用ConfigurationManager.AppSettings(“什么”);建议并返回此值。如果.config文件中没有键可用,可以使用该方法创建某种默认返回。

#13


1  

Also, you can use formo:

你也可以使用formo:

Config:

配置:

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

Code:

代码:

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

#14


1  

As i found best approach to access app settings variables in systematic way by making a wrapper class over System.Configuration as below

我发现了通过在系统上创建包装类来系统地访问应用程序设置变量的最佳方法。配置如下

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

Now we can access needed settings variables by hard coded names using another class as below

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

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
    }

#15


0  

I have been trying to find a fix for this same issue for a couple days now. I was able to resolve this by adding a key within the appsettings tag in the web.config. This should override the .dll when using the helper.

这几天我一直在寻找解决这个问题的办法。我可以通过在web.config中的appsettings标记中添加一个键来解决这个问题。当使用helper时,应该重写.dll。

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

#16


0  

I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wrappers the calls to System.Configuration. All your System.Configuration calls are now in one place so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

我总是使用为所有配置值声明的typesafe属性创建一个IConfig接口。然后,配置实现类封装对System.Configuration的调用。你所有的系统。配置调用现在位于一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和干净。我编写了一组私有助手方法来读取和解析公共数据类型。

Using an IoC framework you can access the IConfig fields anywhere your in app by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.

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

#17


0  

Just for completeness, there's another option available for web projects only:

为了完整起见,这里还有另一个只适用于web项目的选项:

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

The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.

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

#18


0  

Another possible solution:

另一个可能的解决方案:

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

#19


-3  

for ex:

为例:

<applicationSettings>
        <MyApp.My.MySettings>
            <setting name="Printer" serializeAs="String">
                <value>1234 </value>
            </setting>
        </MyApp.My.MySettings>
    </applicationSettings>
Dim strPrinterName as string= My.settings.Printer

#1


641  

You'll need to add a reference to System.Configuration in your project's references folder.

您需要向系统添加一个引用。项目引用文件夹中的配置。

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.

您应该使用ConfigurationManager,而不是过时的ConfigurationSettings。

#2


660  

For Sample App.config like below:

以下是示例App.config:

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

You read the above app settings using code shown below:

您使用如下代码阅读上述应用程序设置:

using System.Configuration;

You may also need to also add a reference to System.Configuration in your project if there isn't one already. You can then access the values like so:

您可能还需要向系统添加一个引用。如果项目中还没有配置的话。然后您可以访问这样的值:

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

Hope this helps!

希望这可以帮助!

#3


51  

Update for framework 4.5 and 4.6; the following will no longer work:

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

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

Now access the Setting class via Properties:

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

string keyvalue= Properties.Settings.Default.keyname;

See Managing Application Settings for more information.

有关更多信息,请参见管理应用程序设置。

#4


34  

Right click on your class Library, and choose the "Add References" option from the Menu; and finally from the .NET tab, select System.Configuration. This would include System.Configuration dll into your project.

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

#5


27  

Im using this and it works well for me

我用这个,它对我很有效

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

#6


18  

You must add to the project a reference to the System.Configuration assembly.

您必须向项目添加对系统的引用。配置组装。

#7


12  

You might be adding the App.config file to a DLL. App.Config works only for executable projects, since all the dll take the configuration from the configuration file for the exe being executed.

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

Let's say you have two projects in your solution:

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

  • SomeDll
  • SomeDll
  • SomeExe
  • SomeExe

Your problem might be releated to the fact that you're including the app.config to SomeDLL and not SomeExe. SomeDll is able to read the configuration from the SomeExe project.

您的问题可能与您将app.config包含到某个dll而不是SomeExe有关。SomeDll可以从SomeExe项目中读取配置。

#8


10  

Read From Config :

读取配置:

You'll need to add a reference to Config

您需要向Config添加一个引用

  1. Open "Properties" on your project
  2. 在项目中打开“属性”
  3. Go to "Settings" Tab
  4. 进入“设置”选项卡
  5. Add "Name" and "Value"
  6. 添加“Name”和“价值”
  7. Get Value with using following code :

    使用以下代码获取值:

    string value = Properties.Settings.Default.keyname;

    字符串值= Properties.Settings.Default.keyname;

Save to Config :

保存到配置:

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

#9


5  

I had the same problem, just read them this way:

我也有同样的问题,就这样读:

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

#10


5  

Try this:

试试这个:

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

In web.config should be next structure:

在网络上。配置应该是下一个结构:

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

#11


4  

web.config is used with web applications.web.config will by default have several configurations required for the web application. You can have a web.config for each folder under your web application.

网络。配置用于web application .web。默认情况下,配置将具有web应用程序所需的多个配置。你可以有一个网络。为web应用程序下的每个文件夹配置。

app.config is used for windows applications. When you build the application in vs.net, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.

config用于windows应用程序。当您在vs.net中构建应用程序时,它将被自动重命名为 .exe。配置文件和这个文件必须与您的应用程序一起交付。

You can use the same method to call the app settings values from both config files :

您可以使用相同的方法从两个配置文件调用app设置值:

System.Configuration.COnfigurationSettings.AppSettings["Key"]

#12


2  

I strongly recommend you to create a Wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

我强烈建议您为这个调用创建一个包装器。类似于ConfigurationReaderService和使用依赖注入来获得这个类。通过这种方式,您将能够为测试目的隔离这个配置文件。

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.

所以使用ConfigurationManager.AppSettings(“什么”);建议并返回此值。如果.config文件中没有键可用,可以使用该方法创建某种默认返回。

#13


1  

Also, you can use formo:

你也可以使用formo:

Config:

配置:

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

Code:

代码:

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

#14


1  

As i found best approach to access app settings variables in systematic way by making a wrapper class over System.Configuration as below

我发现了通过在系统上创建包装类来系统地访问应用程序设置变量的最佳方法。配置如下

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

Now we can access needed settings variables by hard coded names using another class as below

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

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
    }

#15


0  

I have been trying to find a fix for this same issue for a couple days now. I was able to resolve this by adding a key within the appsettings tag in the web.config. This should override the .dll when using the helper.

这几天我一直在寻找解决这个问题的办法。我可以通过在web.config中的appsettings标记中添加一个键来解决这个问题。当使用helper时,应该重写.dll。

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

#16


0  

I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wrappers the calls to System.Configuration. All your System.Configuration calls are now in one place so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

我总是使用为所有配置值声明的typesafe属性创建一个IConfig接口。然后,配置实现类封装对System.Configuration的调用。你所有的系统。配置调用现在位于一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和干净。我编写了一组私有助手方法来读取和解析公共数据类型。

Using an IoC framework you can access the IConfig fields anywhere your in app by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.

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

#17


0  

Just for completeness, there's another option available for web projects only:

为了完整起见,这里还有另一个只适用于web项目的选项:

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

The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.

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

#18


0  

Another possible solution:

另一个可能的解决方案:

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

#19


-3  

for ex:

为例:

<applicationSettings>
        <MyApp.My.MySettings>
            <setting name="Printer" serializeAs="String">
                <value>1234 </value>
            </setting>
        </MyApp.My.MySettings>
    </applicationSettings>
Dim strPrinterName as string= My.settings.Printer