App.config - LocalSqlServer连接字符串

16
请看下方代码:
Public Shared Sub SyncConnectionStrings()
    Dim strCon As String
    Dim tyDatabase As typeDatabase
    Dim boolConfigChanged As Boolean
    'Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim strConnectionString As ConnectionStringSettings            
    For Each strConnectionString In ConfigurationManager.ConnectionStrings
        'More code here, but irrelevant for this question.
    Next
End Sub

该代码循环遍历app.config文件中的所有连接字符串。在app.config中有三个连接字符串,但找到了四个连接字符串。LocalSqlServer定义在哪里?(这是ConfigurationManager.ConnectionStrings.Name)。

2个回答

18

此定义位于 Machine.config 全局文件中,该文件位于

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG".

当您安装NET.Framework时,它会自动生成,并且被ASPNETDB工具所需。

如果您不需要它,可以尝试将此内容添加到您的app.config文件中。

<connectionStrings>
<clear/>
.....

或者也可以

<connectionStrings>
<remove name="LocalSqlServer" />

我强烈建议,除非你知道其副作用,否则不要更改Machine.Config中的任何内容。


2
谢谢 +1。你知道是否有一种方法可以循环遍历 app.config 连接字符串吗? - w0051977
答案已更新,不太确定副作用,但你可以尝试一下,如果出了问题,恢复初始状态即可。 - Steve

8

在Machine.config中可以存在不止LocalSqlServer这个连接字符串,例如我刚才在一个安装了MySql连接的电脑上运行了我的应用程序。

您可以使用ConnectionStringSettingElementInformation属性来确定它是从哪里来的:

foreach (ConnectionStringSettings c in ConfigurationManager.ConnectionStrings)
{
    ElementInformation elementInfo = c.ElementInformation;
    String source = elementInfo.Source;

    if (source == null)
    {
        //Machine.config
    } 
    else
    {
        Console.WriteLine("{0} {1} {2}", c.Name, elementInfo.Source, c.ConnectionString);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接