Search code examples
vb.netliststreamreader

How to return a string from a text file with condition met?


enter image description here

 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

Im try to return some string from a text file, so I use StreamReader to read the file and store them into a list. Now I try to declare a variable to get "localhost" from list of string, but the code below is not work for me.

Dim server As String = Lines.Where(Function(str) str.Contains("server =")).ToString


Solution

  • Enumerable.Where does not return a single string but possibly multiple, using ToString gives you not the first matching line but just the name of the type which is System.Linq.Enumerable+WhereArrayIterator1[System.String].

    Either declare it as IEnumerable(Of String) or use First/ FirstOrDefault to get the first line that matches the condition:

    Dim serverLine As String = Lines
        .Where(Function(str) str.Contains("server ="))
        .FirstOrDefault()
    

    You can also use the overload of FirstOrDefault(Nothing if there was no such line):

    Dim serverLine As String = Lines.FirstOrDefault(Function(str) str.Contains("server ="))
    

    To extract Localhost:

    Dim server As String = serverLine.Substring(serverLine.IndexOf("server =") + "server =".Length).Trim(""""c, " "c)