1. Computing

Simple File Processing and VB.NET



Like the legacy Input function above, Stream supports reading and writing bytes. But it does so much more! A stream could also be data "streaming" in from a network port or a piece of lab equipment. Streaming to a file is just a good introduction to a much larger and more useful technology, but let's see how that works.

Imports System.IO

FileName = "Win.Ini"
Using s As StreamReader = New StreamReader(FileName)
   Dim line As String
      line = s.ReadLine()
   Loop Until line Is Nothing
End Using

The example shows that the familiar ReadLine method is available, but you can also read blocks, entire files, or just Peek at the next character without "consuming" it. Using a StreamReader to read a simple sequential file is a little like driving to the corner store in a 50 ton truck. But it works.

TextFieldParser - A Better CSV

Earlier, I wrote that a better way to read CSV files would be demonstrated. TextFieldParser in Microsoft.VisualBasic.FileIO is the better way. This code (adapted from Microsoft) includes a Using block to declare a new TextFieldParser object. The Using block makes certain that the object is destroyed again when it's not needed at the end. It also checks for problems using a Try-Catch block. But the essential function is that it reads the same CSV file that we saw earlier.

FileName = "CSVFile.txt"
Using CSVReader As New _
   CSVReader.TextFieldType = _
   Dim currentRow As String()
   While Not CSVReader.EndOfData
         currentRow = CSVReader.ReadFields()
         Dim currentField As String
         For Each currentField In currentRow
      Catch ex As _
         MsgBox("Line " & ex.Message & _
         "is not valid and will be skipped.")
      End Try
   End While
End Using

If your file has a different delimiter, just tell TextFieldParser what it is. This line of code allows a file delimited with tab characters to be read.

TabReader.Delimiters = New String() {vbTab}

  1. About.com
  2. Computing
  3. Visual Basic
  4. Using VB.NET
  5. Simple File Processing and VB.NET

©2014 About.com. All rights reserved.