Skip to content

Latest commit

 

History

History
61 lines (39 loc) · 3.39 KB

how-to-read-from-comma-delimited-text-files.md

File metadata and controls

61 lines (39 loc) · 3.39 KB
description title ms.date helpviewer_keywords ms.assetid
Learn more about: How to: read from comma-delimited text files in Visual Basic
How to: read from comma-delimited text files
07/20/2015
files [Visual Basic], parsing
text files [Visual Basic], tasks
reading text files [Visual Basic], comma-delimited
text files [Visual Basic], reading
a8413fe4-0dba-49c8-8692-44fb67a9ec4f

How to: read from comma-delimited text files in Visual Basic

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited file or one with fixed-width fields of text.

To parse a comma delimited text file

  1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.

    [!code-vbVbFileIORead#15]

  2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".

    [!code-vbVbFileIORead#16]

  3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in turn and reporting any fields that are formatted incorrectly.

    [!code-vbVbFileIORead#17]

  4. Close the While and Using blocks with End While and End Using.

    [!code-vbVbFileIORead#18]

Example

This example reads from the file test.txt.

[!code-vbVbFileIORead#19]

Robust programming

The following conditions may cause an exception:

  • A row cannot be parsed using the specified format (xref:Microsoft.VisualBasic.FileIO.MalformedLineException). The exception message specifies the line causing the exception, while the xref:Microsoft.VisualBasic.FileIO.TextFieldParser.ErrorLine%2A property is assigned the text contained in the line.

  • The specified file does not exist (xref:System.IO.FileNotFoundException).

  • A partial-trust situation in which the user does not have sufficient permissions to access the file. (xref:System.Security.SecurityException).

  • The path is too long (xref:System.IO.PathTooLongException).

  • The user does not have sufficient permissions to access the file (xref:System.UnauthorizedAccessException).

See also