HOW TO:在 Visual Basic 中以多種格式從文字檔讀取
更新:2007 年 11 月
TextFieldParser 物件提供簡便且有效的方式來剖析結構化的文字檔,例如記錄檔。您可以使用 PeekChars 方法處理具有多種格式的檔案,以便在剖析整個檔案時判斷每一行的格式。
若要剖析具有多種格式的文字檔
定義預期的格式,以及報告錯誤時要使用的格式。
Dim StdFormat As Integer()= {5,10,11,-1} Dim ErrorFormat As Integer() = {5,5,-1}
建立新的 TextFieldParser 物件,定義格式和寬度。
Using MyReader As New _ Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth
對資料列進行迴圈 (Loop),在讀取之前先測試格式。
Dim CurrentRow As String() While Not MyReader.EndOfData Try Dim RowType As String = MyReader.PeekChars(3) If String.Compare(RowType, "Err") = 0 Then ' If this line describes an error, the format of ' the row will be different. MyReader.SetFieldWidths(ErrorFormat) CurrentRow = MyReader.ReadFields MyReader.SetFieldWidths(StdFormat) Else 'Otherwise parse the fields normally CurrentRow = MyReader.ReadFields For Each newString As String In CurrentRow My.Computer.FileSystem.WriteAllText _ ("newFile.txt", newString, True) Next End If
將錯誤寫入至主控台 (Console)。
Catch ex As _ Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & " is invalid.") End Try End While End Using
範例
這個範例會讀取檔案 testfile.txt。
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = MyReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(ErrorFormat)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
穩固程式設計
下列情形可能會造成例外狀況:
不可以使用指定的格式剖析資料列 (MalformedLineException)。例外狀況訊息會指出造成例外狀況的文字行,而 TextFieldParser.ErrorLine 屬性會指派給此行內含的文字。
指定的檔案不存在 (FileNotFoundException)。
發生使用者權限不足而無法存取檔案的部分信任狀況。 (SecurityException).
路徑太長 (PathTooLongException)。
使用者沒有足夠的使用權限可以存取檔案 (UnauthorizedAccessException)。
請參閱
工作
HOW TO:在 Visual Basic 中從逗號分隔文字檔讀取
HOW TO:在 Visual Basic 中從固定寬度的文字檔讀取