My.Computer.FileSystem.OpenTextFieldParser 方法
更新:2007 年 11 月
OpenTextFieldParser 方法可讓您建立 TextFieldParser 物件,此物件提供簡便且有效的方式剖析結構化的文字檔,例如記錄檔。可使用 TextFieldParser 物件讀取分隔和固定寬度的檔案。
' Usage Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file) Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,delimiters) Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,fieldWidths) ' Declaration Public Function OpenTextFieldParser( _ ByVal file As String _ ) As TextFieldParser ' -or- Public Function OpenTextFieldParser( _ ByVal file As String, _ ByVal delimiters As String() _ ) As TextFieldParser ' -or- Public Function OpenTextFieldParser( _ ByVal file As String, _ ByVal fieldWidths As Integer() _ ) As TextFieldParser
參數
file
String。要使用 TextFieldParser 開啟的檔案。必要項。delimiters
String()。欄位的分隔符號 (Delimiter)。必要項。fieldWidths
Integer()。欄位的寬度。必要項。
傳回值
例外狀況
下列情形可能會造成例外狀況:
因下列其中一項原因而導致路徑無效:它是長度為零的字串、它只包含空白字元、它包含無效的字元,或者它是裝置路徑 (開頭為 \\.\) (ArgumentException)。
檔案名稱以斜線結束 (ArgumentException)。
路徑無效,因為它是 Nothing (ArgumentNullException)。
指定的檔案不存在 (FileNotFoundException)。
指定的檔案正在使用中 (IOException)。
路徑超過系統定義的最大長度 (PathTooLongException)。
路徑中的檔案或目錄名稱含有冒號 (:),或者是無效的格式 (NotSupportedException)。
使用者缺乏必要的使用權限來檢視路徑 (SecurityException)。
不可以使用指定的格式剖析資料列 (MalformedLineException)。將包含在程式行中的文字指定給 TextFieldParser.ErrorLine 屬性時,例外狀況訊息會指定造成例外狀況的程式行。
使用者沒有足夠的使用權限可以存取檔案 (UnauthorizedAccessException)。
工作
下表列出包含 My.Computer.FileSystem.OpenTextFieldParser 方法的工作範例。
若要 |
請參閱 |
---|---|
從有分隔符號的文字檔讀取 |
|
讀取固定寬度的文字檔 |
|
以多種格式讀取文字檔 |
範例
這個範例會開啟 TextFieldParserreader,並使用它讀取 C:\TestFolder1\Test1.txt。
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\TestFolder1\test1.txt")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
需求
命名空間 (Namespace)︰Microsoft.VisualBasic.MyServices
類別 (Class):FileSystemProxy (提供對 FileSystem 的存取)
組件:Visual Basic 執行階段程式庫 (在 Microsoft.VisualBasic.dll 中)
依專案類型的可用性
專案類型 |
是否可用 |
---|---|
Windows 應用程式 |
是 |
類別庫 |
是 |
主控台應用程式 |
是 |
Windows 控制項程式庫 |
是 |
Web 控制項程式庫 |
是 |
Windows 服務 |
是 |
網站 |
是 |
使用權限
下列使用權限可能為必要:
使用權限 |
描述 |
---|---|
控制存取檔案和資料夾的功能。關聯的列舉型別:Unrestricted。 |
|
描述套用至程式碼的一組安全性權限。關聯的列舉型別:ControlEvidence。 |
請參閱
工作
HOW TO:在 Visual Basic 中從逗號分隔文字檔讀取
HOW TO:在 Visual Basic 中以多種格式從文字檔讀取