vb net如何从txt文件中读取每一行
问题描述:
我想阅读一个只有2行的文本文件,并在文本框中显示它们是我的代码(来自MSDN),但无法弄清楚如何继续:
I want to read a text file with only 2 Lines and show them in text boxes here is my code (from MSDN) but cannot figure out how to continue:
Dim fileReader As System.IO.StreamReader
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\Program Files\login.conf")
Dim str1, str2 As String
并且在变量str1中使用txt文件的第一行,在str2中使用第二行,如下所示:
and have the first Line of the txt file in variable str1 and second in str2 like this :
textbox1.text = str1
textbox2.text = str2
答
您可以使用File.ReadAllLines方法,非常容易使用。 https://msdn.microsoft.com/en -us / library / system.io.file.readalllines(v = vs.110).aspx [ ^ ]
https://msdn.microsoft.com/en-us/library/s2tte0y1(ⅴ = vs.110).aspx [ ^ ]
You could just use the File.ReadAllLines method, very easy to use. https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx[^]
https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx[^]
使用File.ReadAllLines方法
Use File.ReadAllLines Method
Public Shared Function ReadAllLines (
path As String
) As String()
示例:
Example:
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
希望它能解决您的问题
hope it would resolve your issue