ConfigurationManager获取项目配置数据
我在项目中创建了一个配置文件,并将其命名为 MyConfig.config。它包含以下内容:
<configuration>
<MySection MyString="StringHere"/>
</configuration>
我正在尝试按如下方式访问此内容:
AppSettingsSection settings = (AppSettingsSection)ConfigurationManager.GetSection("MySection");
string myString = settings.Settings["MyString"].Value;
显然我做错了什么。是否可以以这种方式使用 ConfigurationManager ?
I have created a config file within my project, and called it MyConfig.config. It contains the following:
<configuration>
<MySection MyString="StringHere"/>
</configuration>
I’’m trying to access this as follows:
AppSettingsSection settings = (AppSettingsSection)ConfigurationManager.GetSection("MySection");
string myString = settings.Settings["MyString"].Value;
Clearly I’m doing something wrong. Is it even possible to use the ConfigurationManager in this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的。有几个步骤。首先,您必须在配置中定义您的部分。这涉及声明节名称和类型(您编写的类):
接下来,您必须实际编写代码来处理该节。它必须继承自IConfigurationSectionHandler:
接下来,将实际的配置项添加到web.config中:
完成。
Yes, it is possible. There are a couple of steps. First, you have to define your section in the config. This involves declaring the section name and the type (class you have written):
Next, you have to actually write the code to handle the section. It must inherit from IConfigurationSectionHandler:
Next, add the actual configuration item into the web.config:
Done.
您的配置文件是否被复制到输出目录并重命名为 YourExeFile.exe.config?据我所知,您必须将配置文件命名为 app.config 或在构建后自行复制。
当您想要从备用配置文件加载配置时,可以使用
ConfigurationMangager.OpenMappedConfigurationFile()
方法加载该文件而不是默认配置文件。请参阅 MSDN 了解一个例子。当您想要使用自定义用户定义的配置部分时,您必须提供类来访问该部分。看看这篇好文章 开始吧。
Does you config file gets copied to the output directory and renamed to YourExeFile.exe.config? As far as i know you have to name your config file app.config or copy it by yourself after building.
When you want to load the config form an alternative config file you can use the
ConfigurationMangager.OpenMappedConfigurationFile()
method to load that file instead of the default config file. See MSDN for an example.When you want to use a custom user defined config section, you have to provide classes to access that section. Take a look at this good article to get started.
我认为您不能以这种方式使用配置文件。您是否考虑过使用 .settings 文件?
I don't think you can use the config file in this way. Have you considered using a .settings file?