讀取文字檔案內容使用Visual Basic
過去我的工作曾經有過要用程式讀取文字檔案的經驗,今天就來教大家如何使用Visual Basic讀取文字檔案的內容。
首先新增一個Winform程式使用VB,然後在設計的區塊加入一個RichTextBox並命名為Resultbox如下圖:
一開始撰寫程式記得要引用System.IO,程式碼如下:
Imports System.IO
然後我在程式中使用StreamReader,用一行一行讀取的方式把文字讀取出來,我寫下這行程式:
Dim filereader = My.Computer.FileSystem.OpenTextFileReader("D:\doc\Text.txt", System.Text.Encoding.Default)
程式中filereader他會根據後面的程式自動轉換為StreamReader,在新版的Visual Basic中這裡是可以省略As StreamReader的,D:\doc\Text.txt這裡記得改成你的文字檔路徑,System.Text.Encoding.Default這是設定文字編碼格式為預設。
然後我在程式中用While迴圈把每一行文字給讀取出來,如下:
Dim text As String = ""
Dim line As String = filereader.ReadLine()
While Not (line Is Nothing)
text = text & line & vbCrLf
line = filereader.ReadLine()
End While
最後就是把開啟的StreamReader關閉,然後把讀取出來的文字顯示在RichTextBox,程式如下:
filereader.Close()
Resultbox.Text = text
程式執行結果如下:
功能陽春的文字讀取程式就完成了,實際工作上運用到時會需要做一些進階的功能,這個我下次再介紹。
這個專案的完整程式碼如下:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filereader = My.Computer.FileSystem.OpenTextFileReader("D:\doc\Text.txt", System.Text.Encoding.Default)
Dim text As String = ""
Dim line As String = filereader.ReadLine()
While Not (line Is Nothing)
text = text & line & vbCrLf
line = filereader.ReadLine()
End While
filereader.Close()
Resultbox.Text = text
End Sub
End Class
留言列表