我的项目中有一个config.ini文件,这是我的ini文件中的数据保存,如下所示。 config 其中DESKTOP-UAGO7SB \ SQLEXPRESS是数据源,admin是uid,xxxx是pwd 我有一个以下代码来读取我的模块中的config.ini文件中的数据
Public Function checkServer() As Boolean
Try
With frmSettings
.OpenFileDialog1.FileName = Application.StartupPath & "\Config.ini"
openedFileStream = .OpenFileDialog1.OpenFile()
End With
ReDim dataBytes(openedFileStream.Length - 1) 'Init
openedFileStream.Read(dataBytes, 0, openedFileStream.Length)
openedFileStream.Close()
tmpStr = System.Text.Encoding.Unicode.GetString(dataBytes)
With frmSettings
If Split(tmpStr, ":")(4) = "1" Then
'network
CnString = "Data Source=" & Split(tmpStr, ":")(0) & _
";database=DBMISO" & _
";uid=" & Split(tmpStr, ":")(2) & _
";pwd=" & Split(tmpStr, ":")(3)
Else
'local
'MsgBox(Split(tmpStr, ":")(1))
CnString = "Data Source=" & Split(tmpStr, ":")(1) & _
";Database=DBMISO; Trusted_Connection=yes;"
End If
End With
Dim sqlCon As New SqlConnection
sqlCon.ConnectionString = CnString
sqlCon.Open()
checkServer = True
sqlCon.Close()
Catch ex As Exception
checkServer = False
End Try
End Function
每当我调用CnString来连接数据库时,它都会给我一个错误
ConnectionString属性尚未初始化
答案 0 :(得分:0)
许多事情在您的代码中没有意义或者是完全错误的 您正在使用.NET,因此您应该使用Framework类和方法,而不是仅为兼容性而维护的旧Visual Basic函数
Try
' Read all the text from your config file
Dim configData = File.ReadAllText(Application.StartupPath & "\Config.ini")
' Split it once and for all
Dim configParts = configData.Split(":"c)
' You expect your config to have at least 4 parts
if configParts.Length >= 4 Then
' Arrays start at zero so the 1 is at index 3 not 4
If configParts(3) = "1" Then
' Again, arrays start at index zero.....
CnString = "Data Source=" & configParts(0) & _
";database=DBMISO" & _
";uid=" & configParts(1) & _
";pwd=" & configParts(2)
Else
'local
CnString = "Data Source=" & configParts(0) & _
";Database=DBMISO; Trusted_Connection=yes;"
End If
' Enclose in a using statement to dispose the connection also in case
' of exceptions
Using sqlCon = New SqlConnection(CnString)
sqlCon.Open()
checkServer = True
End Using
Else
MessageBox.Show("Incorrect config.ini")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
return checkServer
在完成所有这些工作后,您可能应该考虑.NET具有经过验证的基础架构来处理连接字符串和配置文件。您应该停止使用此方法并了解how to use a configuration file以及如何处理connection string from a config file
答案 1 :(得分:0)
假设您有一个名为“YourConnectionStringName”的字符串,这应该有效:
Dim cnString As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("YourConnectionStringName").ConnectionString
您需要添加对System.Web的引用。