【问题标题】:How to return a string from a text file with condition met?如何从满足条件的文本文件中返回字符串?
【发布时间】:2017-05-23 07:31:59
【问题描述】:

 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

【问题讨论】:

  • 服务器字符串给你什么回报

标签: vb.net list streamreader


【解决方案1】:

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)

【讨论】:

  • 快让我有时间回复哈哈。我喜欢 FirstOrDefault 方法投票!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
相关资源
最近更新 更多