ReadAllText 物件的 My.Computer.FileSystem 方法可讓您從文字檔讀取。 如果檔案的內容使用 ASCII 或 UTF-8 等編碼方式,則可以指定檔案編碼。
如果您要從具有擴充字元的檔案讀取,則必須指定檔案編碼。
備註
若要一次讀取單行文字檔案,請使用 OpenTextFileReader 物件的方法 My.Computer.FileSystem 。
OpenTextFileReader 方法會傳回 StreamReader 物件。 利用 ReadLine 物件中的 StreamReader 方法來一次讀取一行檔案。 您可以使用EndOfStream物件的StreamReader方法測試檔案結尾。
從文字檔讀取
使用ReadAllText物件的My.Computer.FileSystem方法,將文本文件的內容讀入字串,並提供路徑。 下列範例會將 test.txt 的內容讀入字串,然後在消息框中顯示。
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("test.txt")
MsgBox(fileReader)
從編碼的文字檔讀取
使用ReadAllText物件的My.Computer.FileSystem方法,將文本檔案的內容讀入字串,並指定路徑和檔案編碼類型。 下列範例會將UTF32檔案的內容讀入字串中 test.txt,然後將它顯示在消息框中。
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("test.txt",
System.Text.Encoding.UTF32)
MsgBox(fileReader)
從文字檔讀取至 RichTextBox 控制項
若要將文字檔的內容直接載入 RichTextBox 控制項,請將檔案內容讀取為字串,並將它指派給 Text RichTextBox 的屬性。 下列範例示範如何讀取文字檔,並將它載入 RichTextBox 控制項。
' Load text file into a RichTextBox control
' Note: This assumes RichTextBox1 is a control on your form
Dim fileText As String
fileText = My.Computer.FileSystem.ReadAllText("test.txt")
' RichTextBox1.Text = fileText
為了更好地處理錯誤和檔案路徑管理,您可以使用下列方法來建構適當的檔案路徑並處理潛在的例外狀況。 此方法可避免硬式編碼磁碟機路徑,以免在不同系統上造成問題:
' Load text file into a RichTextBox control using a specific path
Try
Dim filePath As String = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "test.txt")
Dim fileText As String = My.Computer.FileSystem.ReadAllText(filePath)
' RichTextBox1.Text = fileText
Catch ex As System.IO.FileNotFoundException
MsgBox("File not found: " & ex.Message)
Catch ex As Exception
MsgBox("Error reading file: " & ex.Message)
End Try
備註
指定檔案路徑時,請避免使用硬編碼的絕對路徑,例如「C:\temp\file.txt」,因為這些路徑可能會在磁碟機代號或目錄結構不同的系統上導致問題。 相反地,請使用相對路徑或利用Combine功能來建構路徑,以確保您的程式碼可以在不同環境中運作。
健全的程式設計
以下條件可能會造成例外狀況:
路徑無效,原因如下:它是長度為零的字串、只包含空格符、包含無效字元,或是裝置路徑 (ArgumentException)。
路徑是無效的,因為它是
Nothing(ArgumentNullException)。檔案不存在 (FileNotFoundException)。
檔案正由另一個進程使用,或發生 I/O 錯誤 (IOException)。
路徑超過系統定義的最大長度 (PathTooLongException)。
路徑中的檔案或目錄名稱包含冒號(:)或格式無效 (NotSupportedException)。
記憶體不足,無法將字串寫入緩衝區 (OutOfMemoryException)。
使用者缺少檢視路徑的必要許可權(SecurityException)。
請勿根據檔案名稱來判斷檔案內容。 例如,檔案 Form1.vb 可能不是 Visual Basic 來源檔案。
在應用程式中使用這些資料之前,請先驗證所有輸入值。 檔案的內容可能不是預期的內容,而且從檔案讀取的方法可能會失敗。