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

Rus*_*ark 764 .net c# configuration appsettings

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

我发现了

ConfigurationSettings.AppSettings.Get("MySetting")
Run Code Online (Sandbox Code Playgroud)

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

我读过我应该使用的:

ConfigurationManager.AppSettings["MySetting"]
Run Code Online (Sandbox Code Playgroud)

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

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

Ram*_*Ram 837

对于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>
Run Code Online (Sandbox Code Playgroud)

您使用以下代码阅读上述应用设置:

using System.Configuration;
Run Code Online (Sandbox Code Playgroud)

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

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 我比你接受的答案更喜欢你的回答.带有示例的答案总是对我有用. (118认同)
  • 这也发生在我身上.您是否尝试过添加System.Configuration参考?问题是,VS让你认为你真的拥有它会欺骗你; 您可以使用intellisense获取命名空间System.Configuration但它没有ConfigurationManager类.只需添加引用即可修复它. (11认同)
  • @Cricketheads System.Configuration确实包含ConfigurationManager,您可能在项目中缺少对System.Configuration的引用. (2认同)
  • 有人能告诉我为什么他们认为 System.Configuration 不是默认添加的......这在大多数应用程序中似乎是一个非常基本的需求。 (2认同)

wom*_*omp 766

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

你绝对应该使用ConfigurationManager过时的ConfigurationSettings.

  • 这对于 .net core 来说仍然准确吗? (3认同)

bsi*_*vel 74

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

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];
Run Code Online (Sandbox Code Playgroud)

现在通过Properties访问Setting类:

string keyvalue= Properties.Settings.Default.keyname;
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅管理应用程序

  • 无法确认.ConfigurationManager.AppSettings ["someKey"]适用于.NET 4.5,4.6,4.7.1 (5认同)
  • 不适用于 vs2022,这是一个非常过时的答案 (3认同)
  • 自 [2010](https://msdn.microsoft.com/library/a65txexh(v=vs.100).aspx]) 以来的属性。 (2认同)
  • 非常感谢您发布此内容。我确定 Properties.Settings.Default.MachName 有效,但我无法弄清楚为什么 ConfigurationManager.AppSettings["MachName"] 返回 null。 (2认同)
  • 这结束了我长久以来的痛苦。谢谢。框架应该警告您旧的方法已经过时了。 (2认同)

Shi*_*iva 37

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


小智 28

我使用这个,它适合我

textBox1.Text = ConfigurationManager.AppSettings["Name"];
Run Code Online (Sandbox Code Playgroud)

  • TS明确指出,他使用相同的代码,但他的项目无法编译(由于缺少引用,结果).-1不读问题. (48认同)

Mas*_*ali 22

从配置中读取:

您需要添加对Config的引用

  1. 在项目中打开"属性"
  2. 转到"设置"标签
  3. 添加"名称"和"值"
  4. 使用以下代码获取价值:

    string value = Properties.Settings.Default.keyname;

保存到配置:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();
Run Code Online (Sandbox Code Playgroud)


Otá*_*cio 21

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


小智 17

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

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

  • SomeDll
  • SomeExe

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


Rus*_*lan 10

试试这个:

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];
Run Code Online (Sandbox Code Playgroud)

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

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

  • 这个问题已经得到了很好的接受答案..你想说什么? (4认同)

Tom*_*Tom 8

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

System.Configuration.ConfigurationSettings.AppSettings["MySetting"]
Run Code Online (Sandbox Code Playgroud)

  • 根据微软关于ConfigurationSettings.AppSettings`这个方法已经过时,它已被System.Configuration取代!System.Configuration.ConfigurationManager.AppSettings` (4认同)
  • 这种方法已经过时了 (2认同)

Jit*_*har 8

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

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

第 3 步:搜索“System.Configuration”

第四步:点击确定。

然后它会起作用。

 string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];
Run Code Online (Sandbox Code Playgroud)


小智 7

web.config用于Web应用程序.web.config默认情况下,Web应用程序需要多个配置.您可以web.config为Web应用程序下的每个文件夹添加一个.

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

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

System.Configuration.ConfigurationSettings.AppSettings["Key"]
Run Code Online (Sandbox Code Playgroud)


pom*_*ber 6

另外,您可以使用Formo

配置:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

代码:

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>();
Run Code Online (Sandbox Code Playgroud)

  • 你到底为什么要这么做? (6认同)

小智 5

当我发现通过在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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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
    }
Run Code Online (Sandbox Code Playgroud)


Chr*_*ani 5

如果您需要/想要使用该ConfigurationManager课程...

您可能需要System.Configuration.ConfigurationManager由 Microsoft 通过NuGet Package Manager加载

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

微软文档

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

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