以下程式碼, 由上而下分別是:
(1) 以 File.Open 讀檔
(2) 以 StreamReader 讀檔(此方法比較簡便)
(3) 以 File 類別支援的 ReadAllText 方法, 讀出整個檔案內容.
(4) StreamReader 搜尋檔案裡是否存在某個字串.
因為程式碼都很簡單, 就不多做解釋, 請直接看以下所附的 code 應該不難了解.
Imports System.IO
Public Class _03_StreamReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim theFile As FileStream = File.Open("d:\temp\asdf.txt", FileMode.Open, FileAccess.Read)
Dim rdr As StreamReader = New StreamReader(theFile)
TextBox1.Text = rdr.ReadToEnd()
rdr.Close()
theFile.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim rdr As StreamReader = File.OpenText("d:\temp\asdf.txt")
TextBox1.Text = rdr.ReadToEnd()
rdr.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
MsgBox(File.ReadAllText("d:\temp\asdf.txt"))
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim rdr As StreamReader = File.OpenText("d:\temp\asdf.txt")
While Not rdr.EndOfStream
Dim ft As String = rdr.ReadLine()
If ft.Contains(TextBox2.Text) Then
MsgBox("Found " & TextBox2.Text & vbNewLine & ft)
End If
End While
End Sub
End Class
沒有留言:
張貼留言