TextFieldParser.FieldWidths 屬性

定義

代表正在剖析文字檔中每一個資料行的寬度。

C#
public int[]? FieldWidths { get; set; }
C#
public int[] FieldWidths { get; set; }

屬性值

Int32[]

整數陣列,其中包含正在剖析之文字檔中每一個資料行的寬度。

例外狀況

任何位置 (除了陣列的最後一個項目以外) 中的寬度值會小於或等於零。

範例

本範例會讀取檔案 ParserText.txt,指定寬度;第一欄寬為 5 個字元,第二欄為 10,第三欄為 11,第四個為可變寬度

VB
Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("C:\ParserText.txt")

    MyReader.TextFieldType = 
        Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = {5, 10, 11, -1}
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.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
End Using

備註

只有當 屬性設定為 FieldType.FixedWidth時,TextFieldType這個屬性才有意義。 如果陣列中的最後一個專案小於或等於零,則字段會假設為可變寬度。

方法 SetFieldWidths 也可以用來設定欄位寬度。

下表列出涉及 FieldWidths 屬性的工作範例。

收件者 請參閱
從固定寬度文本檔讀取 作法:從固定寬度的文字檔讀取

適用於

產品 版本
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另請參閱