从 Windows 窗体应用程序中保存新的连接字符串?

发布于 2024-12-01 15:10:10 字数 2503 浏览 0 评论 0原文

我正在编写一个 Windows 窗体应用程序,VS2010,NET Framework 4.0,用 VB 编码。我在应用程序中使用 Microsoft 数据连接配置对话框来选择数据源。它似乎工作正常并正确创建 ConnectionString。但是,新的连接字符串不会保存到 app.config 文件中。我没有编写保存文件的代码,我在这方面盲目地徘徊。这是我正在使用的代码:

  Public Sub SaveConnectionString(ByVal strConnectionName As String, strConnectionString As String)

    Dim Config As Configuration
    Dim Section As ConnectionStringsSection
    Dim Setting As ConnectionStringSettings
    Dim ConnectionFullName As String

    'There is no inbuilt way to change application 
    'setting values in the config file.
    'So that needs to be done manually by calling config section object.

    Try
        'Concatenate the full settings name
        'This differs from Jakob Lithner. Runtime Connection Wizard
        'The ConnectionFullName needs to 
        'refer to the Assembly calling this DLL

        ConnectionFullName = String.Format("{0}.MySettings.{1}", _
            System.Reflection.Assembly.GetCallingAssembly.EntryPoint.DeclaringType.Namespace, strConnectionName)

        'Point out the objects to manipulate
        Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Section = CType(Config.GetSection("connectionStrings"),  _
            ConnectionStringsSection)
        Setting = Section.ConnectionStrings(ConnectionFullName)

        MsgBox("To File: " & Config.FilePath.ToString & vbCrLf &
               "Conn. String: " & strConnectionString & vbCrLf &
               "Conn. Name: " & strConnectionName,
               MsgBoxStyle.Information, "Saving Connection String...")

        'Ensure connection setting is defined 
        '(Note: A default value must be set to save the connection setting!)
        If IsNothing(Setting) Then Throw New Exception("There is no connection with this name defined in the config file.")

        'Set value and save it to the config file
        'This differs from Jakob Lithner. Runtime Connection Wizard
        'We only want to save the modified portion of the config file 
        Setting.ConnectionString = strConnectionString
        Config.Save(ConfigurationSaveMode.Full, True)

    Catch ex As Exception

    End Try
End Sub

MsgBox 显示 .config 文件的预期文件名和路径,但该文件从未更新。我尝试过从 VS2010 IDE 运行,直接运行编译创建的 .exe 文件,创建安装程序并安装程序并运行(程序本身运行良好),然后安装在另一台机器上。始终相同 - 没有错误消息,并且 .config 文件不会更新。

该程序正在从 appname.exe.config 文件中读取连接字符串。如果我手动编辑 exe.config 文件,我可以毫无问题地使用不同的连接字符串。

如果有人可以提供任何指导,我将非常感激!提前致谢。

I'm writing a Windows Forms app, VS2010, NET Framework 4.0, coding in VB. I'm using the Microsoft Data Connection Configuration dialog in my app to choose a data source. It seems to work fine and creates the ConnectionString correctly. However, the new connection string is not being saved to the app.config file. I did not write the code to save the file and I'm staggering around blindly in this area. Here's the code I'm using:

  Public Sub SaveConnectionString(ByVal strConnectionName As String, strConnectionString As String)

    Dim Config As Configuration
    Dim Section As ConnectionStringsSection
    Dim Setting As ConnectionStringSettings
    Dim ConnectionFullName As String

    'There is no inbuilt way to change application 
    'setting values in the config file.
    'So that needs to be done manually by calling config section object.

    Try
        'Concatenate the full settings name
        'This differs from Jakob Lithner. Runtime Connection Wizard
        'The ConnectionFullName needs to 
        'refer to the Assembly calling this DLL

        ConnectionFullName = String.Format("{0}.MySettings.{1}", _
            System.Reflection.Assembly.GetCallingAssembly.EntryPoint.DeclaringType.Namespace, strConnectionName)

        'Point out the objects to manipulate
        Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Section = CType(Config.GetSection("connectionStrings"),  _
            ConnectionStringsSection)
        Setting = Section.ConnectionStrings(ConnectionFullName)

        MsgBox("To File: " & Config.FilePath.ToString & vbCrLf &
               "Conn. String: " & strConnectionString & vbCrLf &
               "Conn. Name: " & strConnectionName,
               MsgBoxStyle.Information, "Saving Connection String...")

        'Ensure connection setting is defined 
        '(Note: A default value must be set to save the connection setting!)
        If IsNothing(Setting) Then Throw New Exception("There is no connection with this name defined in the config file.")

        'Set value and save it to the config file
        'This differs from Jakob Lithner. Runtime Connection Wizard
        'We only want to save the modified portion of the config file 
        Setting.ConnectionString = strConnectionString
        Config.Save(ConfigurationSaveMode.Full, True)

    Catch ex As Exception

    End Try
End Sub

The MsgBox shows the expected file name and path for the .config file but the file is never updated. I've tried this running from the VS2010 IDE, directly running the .exe file created by the compile, creating a Setup and installing the program and running that (program itself runs fine), and installing on a different machine. Always the same - no error messages and the .config file is not updated.

The program is reading the connection string from the appname.exe.config file. If I edit the exe.config file manually I can use different connection strings without problems.

If anyone can offer any guidance, I'll be VERY appreciative! Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫烠⑼条掵仅有一顆心 2024-12-08 15:10:10

我的问题有相当多的页面浏览量,但没有冒险回答。幸运的是我找到了自己的答案。感谢 http://www.thecodemonk.com/2008/02/18 /tableadapter-connection-strings 这个简单的解决方案。

甚至不要尝试保存到应用程序设置“AppNameConnectionString”。相反,只需将所需的连接字符串保存为用户设置,即字符串类型的“ActiveConnectionString”。我用这个替换了我在原始问题中引用的整个代码块。

       My.Settings.ActiveConnectionString = strConn ' previously built conn string
       My.Settings.Save()

什么允许此用户设置成为活动连接字符串是与 .Net 管理设置相关的事件。在项目设置上有一个“查看代码”按钮来访问设置的事件处理程序。在 SettingsLoaded 事件中,只需将应用程序连接字符串设置设置为您的用户连接字符串设置:

       Private Sub MySettings_SettingsLoaded(sender As Object, e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded
        Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
    End Sub

这就是您的用户设置在应用程序加载时成为工作连接字符串所需的全部内容。

在设置代码中添加另一个事件处理程序,当您从应用程序内保存新的连接字符串时,它将立即激活!

    Private Sub MySettings_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Handles Me.PropertyChanged
        If e.PropertyName = "ActiveConnectionString" Then
            Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
        End If
    End Sub

再次感谢 TheCodeMonk 分享这个极其简单但显然非常难以捉摸的解决方案!

A fair number of page views to my question, but no answers ventured. Fortunately I found my own answer. Thanks to http://www.thecodemonk.com/2008/02/18/tableadapter-connection-strings for this simple solution.

Don't even try to save to the application setting "AppNameConnectionString". Instead, just save the desired connection string as a user setting, i.e. "ActiveConnectionString" of type string. I replaced the whole block of code I quoted in my original question with this

       My.Settings.ActiveConnectionString = strConn ' previously built conn string
       My.Settings.Save()

What allows this user setting to become the active connection string are the events associated with .Net managing the settings. On the Project settings there is a button "view code" to access the event handlers of the settings. In the SettingsLoaded event, just set the app connection string setting to your user connection string setting:

       Private Sub MySettings_SettingsLoaded(sender As Object, e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded
        Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
    End Sub

That's all it takes for your user setting to become the working connection string when the app loads.

Add another event handler in the Settings code and when you save a new connection string from within the app it will be instantly activated!

    Private Sub MySettings_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Handles Me.PropertyChanged
        If e.PropertyName = "ActiveConnectionString" Then
            Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
        End If
    End Sub

Thanks again to TheCodeMonk for sharing this stunningly simple, but apparently very elusive solution!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文