Public Sub openDB()
Dim Lines As New List(Of String)
Try
' Open the file using a stream reader.
Using sr As New StreamReader("Config.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadLine()
Do Until String.IsNullOrEmpty(line)
Lines.Add(line)
line = sr.ReadLine
Loop
End Using
Catch e As Exception
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Dim dbname As String = g_DatabaseName
Dim server As String = Lines.Where(Function(str) str.Contains("server =")).ToString
Dim user As String = ""
Dim password As String = ""
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false; Convert Zero Datetime=True", server, user, password, dbname)
conn.Open()
End Sub
我尝试从文本文件中返回一些字符串,因此我使用StreamReader读取文件并将它们存储到列表中。现在我尝试声明一个变量从字符串列表中获取“localhost”,但下面的代码对我来说不起作用。
Dim server As String = Lines.Where(Function(str)str.Contains(“server =“))。的ToString
答案 0 :(得分:2)
Enumerable.Where
不返回单个字符串,但可能是多个字符串,使用ToString
不会为您提供第一个匹配的行,而只是System.Linq.Enumerable+WhereArrayIterator1[System.String]
类型的名称。
将其声明为IEnumerable(Of String)
或使用First
/ FirstOrDefault
来获取符合条件的第一行:
Dim serverLine As String = Lines
.Where(Function(str) str.Contains("server ="))
.FirstOrDefault()
如果没有这样的行,您也可以使用FirstOrDefault
的重载(Nothing
):
Dim serverLine As String = Lines.FirstOrDefault(Function(str) str.Contains("server ="))
提取Localhost
:
Dim server As String = serverLine.Substring(serverLine.IndexOf("server =") + "server =".Length).Trim(""""c, " "c)