【发布时间】:2011-08-26 00:36:52
【问题描述】:
我正在编写一个 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 文件,我可以毫无问题地使用不同的连接字符串。
如果有人可以提供任何指导,我将非常感激!提前致谢。
【问题讨论】:
-
在这里找到我自己的答案 - [链接] (thecodemonk.com/2008/02/18/tableadapter-connection-strings)
标签: winforms connection-string configuration-files