在文件中查找包含某个字符串的行
Find a line containing a certain string in a file
尝试线性搜索文件以在格式为“,”的文件中找到以用户名(和“,”开头的行,因为它确保它是整个用户名)每一行。
我不知道该怎么做,所以非常感谢您的帮助。
Dim lineCorrect As String = ""
Using reader As New System.IO.StreamReader("Pass.txt")
While Not reader.EndOfStream
If reader.ReadLine.StartsWith(tbUsernameLogIn.Text & ",") = True Then
lineCorrect = reader.ReadLine
Else
reader.ReadLine()
End If
End While
End Using
If lineCorrect = "" Then
Debug.WriteLine("Incorrect Login 1")
Else
'do something'
End If
尝试这样的事情:
Dim lineCorrect As String
lineCorrect = File.ReadLines("Pass.txt") _
.FirstOrDefault(Function(str) str.StartsWith(tbUsernameLogIn.Text & ","))
这是使用 File.ReadLines 方法的简单方法
Dim lineCorrect As String = ""
Dim userLine = tbUsernameLogIn.Text & ","
for Each line in File.ReadLines("Pass.txt")
If line.StartsWith(userLine) Then
lineCorrect = line
Exit For
End If
Next
If lineCorrect = "" Then
Debug.WriteLine("Incorrect Login 1")
Else
'do something'
End If
这允许您枚举文件中的所有行,并在搜索到的行第一次出现时退出 for each 循环。另请注意微优化。保持字符串的构建以在循环外进行检查(尽管编译器可能会自行优化它)
尝试线性搜索文件以在格式为“,”的文件中找到以用户名(和“,”开头的行,因为它确保它是整个用户名)每一行。
我不知道该怎么做,所以非常感谢您的帮助。
Dim lineCorrect As String = ""
Using reader As New System.IO.StreamReader("Pass.txt")
While Not reader.EndOfStream
If reader.ReadLine.StartsWith(tbUsernameLogIn.Text & ",") = True Then
lineCorrect = reader.ReadLine
Else
reader.ReadLine()
End If
End While
End Using
If lineCorrect = "" Then
Debug.WriteLine("Incorrect Login 1")
Else
'do something'
End If
尝试这样的事情:
Dim lineCorrect As String
lineCorrect = File.ReadLines("Pass.txt") _
.FirstOrDefault(Function(str) str.StartsWith(tbUsernameLogIn.Text & ","))
这是使用 File.ReadLines 方法的简单方法
Dim lineCorrect As String = ""
Dim userLine = tbUsernameLogIn.Text & ","
for Each line in File.ReadLines("Pass.txt")
If line.StartsWith(userLine) Then
lineCorrect = line
Exit For
End If
Next
If lineCorrect = "" Then
Debug.WriteLine("Incorrect Login 1")
Else
'do something'
End If
这允许您枚举文件中的所有行,并在搜索到的行第一次出现时退出 for each 循环。另请注意微优化。保持字符串的构建以在循环外进行检查(尽管编译器可能会自行优化它)