C# 如何读取设置文件创建的连接字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10728003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do read connection string created by the settings file?
提问by developer747
When I just had an app.config, everytime I tried ConfigurationManager.AppSettings[0] or ConfigurationManager.AppSettings["keyName"] I got a null. So I tried to use a *.settings file which created me an app.config that looked like this
当我只有一个 app.config 时,每次我尝试 ConfigurationManager.AppSettings[0] 或 ConfigurationManager.AppSettings["keyName"] 时,我都会得到一个空值。所以我尝试使用一个 *.settings 文件,它为我创建了一个看起来像这样的 app.config
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="IndexLoader.IndexLoader" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<IndexLoader.IndexLoader>
<setting name="ConnectionString" serializeAs="String">
<value>INITIAL CATALOG=xxx;DATA SOURCE=xxx;User ID=xxx;Password=xxx;Application Name=xxx;</value>
</setting>
</IndexLoader.IndexLoader>
</applicationSettings>
</configuration>
Now how do I read this connection string using C#?
现在如何使用 C# 读取此连接字符串?
The solution has multiple projects and many of them have config files. Is there a way to specify that I want the config file in code's project to be used?
该解决方案有多个项目,其中许多都有配置文件。有没有办法指定我想要使用代码项目中的配置文件?
采纳答案by Steve
applicationSettingsis not appSettings.
To read an entry in applicationSettings you use
applicationSettings不是appSettings。要读取 applicationSettings 中的条目,您使用
string myCnStr = Properties.Settings.Default.ConnectionString;
In your case it will be
在你的情况下,它将是
string myCnStr =IndexLoader.IndexLoader.Default.ConnectionString;
However the ConnectionString has a dedicated section in the app.config and should be stored there and read from the ConfigurationManager.ConnectionStrings collection
但是 ConnectionString 在 app.config 中有一个专用部分,应该存储在那里并从 ConfigurationManager.ConnectionStrings 集合中读取
See herefor references
请参阅此处以获取参考

