在返回null ConfigurationManager.AppSettingsnull、ConfigurationManager、AppSettings

2023-09-03 07:32:51 作者:背叛

我使用ConfigurationManager.AppSettings [的myKey]读取从我的Windows应用程序在app.config文件中的值,但返回的值总是空,即使键存在,它有一个值,迪斯任何一个知道为什么呢?

I am using ConfigurationManager.AppSettings[myKey] to read a value from the app.config file in my windows application, but the value returned is always null, even though the key exists and it has a value, Deas any one know why?

感谢

推荐答案

一,也许更容易,另一种方法是使用一个设置文件。这种封装的创建和维护的App.config值的设计师GUI和产生code访问的值。

One, perhaps easier, alternative is to use a Settings file. This encapsulates the creation and maintenance of App.config values in a designer GUI and generates code for accessing the values.

要添加一个设置文件,右击VS中的项目,然后单击添加 - >新建项目,选择设置文件,并给它一个有意义的名称,例如: MainSettings.settings 。然后,您可以添加项目,例如,指定其为应用程序或用户范围,定义它的类型和它分配一个值。在您的code,你可以通过简单的书面retreive值 MainSettings.Default.Foo

To add a Settings file, right click your project in VS and click 'Add -> New Item', select 'Settings file' and give it a meaningful name, e.g. MainSettings.settings. You can then add an item, e.g. Foo, specify whether it is application or user-wide, define it's type and a assign it a value. In your code you can retreive the value by simple writing MainSettings.Default.Foo.

编译后,您可以通过编辑配置文件更改该值。会出现设置如下: -

After compilation, you can change the value by editing the config file. The setting will appear as follows:-

<applicationSettings>
    <YourNamespace.MainSettings>
        <setting name="Foo" serializeAs="String">
            <value>Bar</value>
        </setting>
    </YourNamespace.MainSettings>
</applicationSettings>