TextFieldParser物件提供輕鬆且有效率地剖析結構化文本檔的方式,例如記錄檔。 您可以使用 PeekChars 方法來處理具有多種格式的檔案,藉由在剖析檔案時判斷每一行的格式。
剖析具有多種格式的文字檔
將名為 testfile.txt 的文字檔新增至您的專案。 將下列內容新增至文字檔:
Err 1001 Cannot access resource. Err 2014 Resource not found. Acc 10/03/2009User1 Administrator. Err 0323 Warning: Invalid access attempt. Acc 10/03/2009User2 Standard user. Acc 10/04/2009User2 Standard user.定義預期的格式,以及報告錯誤時所使用的格式。 每個陣列中的最後一個元素是 -1,因此會假設最後一個欄位是可變寬度。 當陣列中的最後一個元素小於或等於0時,就會發生此情況。
Dim stdFormat As Integer() = {5, 10, 11, -1} Dim errorFormat As Integer() = {5, 5, -1}建立新的 TextFieldParser 物件,定義寬度和格式。
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth MyReader.FieldWidths = stdFormat遍歷行,在讀取之前先檢測格式。
Dim currentRow As String() While Not MyReader.EndOfData Try Dim rowType = 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) Else ' Otherwise parse the fields normally MyReader.SetFieldWidths(stdFormat) End If currentRow = MyReader.ReadFields For Each newString In currentRow Console.Write(newString & "|") Next Console.WriteLine()將錯誤寫入主控台。
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 FileIO.TextFieldParser("..\..\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = 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)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Console.ReadLine()
穩固程式設計
以下條件可能會造成例外狀況:
- 無法剖析資料列,因為無法使用指定的格式。MalformedLineException 例外狀況訊息會指定造成例外狀況的行,而 ErrorLine 屬性會指派給該行中包含的文字。
- 指定的檔案不存在 (FileNotFoundException)。
- 用戶沒有足夠的許可權存取檔案的部分信任狀況。 (SecurityException)。
- 路徑太長(PathTooLongException)。
- 用戶沒有足夠的許可權可存取檔案 (UnauthorizedAccessException)。