4.2.1.3 - Text and binary files (VB.NET)

4.2.1.3 - Text and binary files (VB.NET)

Read and write text and binary data, keep file formats consistent, and test file-processing boundaries in VB.NET. This route uses written code with no Run: incomplete: runnable support pending.

Fields, records and file organisation

Persistent files retain data after a program ends, but a reader must know how their data are organised.

A field holds one value, such as a product name or quantity; a record groups the fields for one item. A text file could store Pen,12 on one line, with a comma separating two fields and the newline separating records. The reader must know the order and types. In this simple format product names cannot contain commas or newlines; a real general CSV format needs quoting rules.

Text and binary files

A text file stores encoded characters interpreted as text. A binary data format stores values using an agreed byte layout, which need not represent readable characters.

Both are ultimately bytes. The distinction concerns their interpretation, not whether a computer uses binary. Text numbers such as 120 must be parsed from characters. An Integer written by .NET's BinaryWriter uses a four-byte signed integer representation and is read with ReadInt32. Binary does not automatically mean encrypted, compressed or smaller for every possible dataset.

Before reading, specify record boundaries, field order, types and encoding where relevant. Opening an output file in overwrite mode replaces old contents; append mode adds data at the end. File access can fail because a path is missing, permission is denied or data are truncated. Correct handling reports a meaningful failure rather than silently treating it as a valid empty file.

Text-file reading and writing

Text streams convert between characters and bytes while a program reads or writes lines.

This complete source overwrites scores.txt, then reads each line and totals the integers. The expected file consists of three lines: 6, 9 and 0.

VB.NET
Option Strict On
Imports System
Imports System.IO
Module Program
    Sub Main()
        Using writer As New StreamWriter("scores.txt", False)
            writer.WriteLine(6)
            writer.WriteLine(9)
            writer.WriteLine(0)
        End Using
        Dim total As Integer = 0
        Using reader As New StreamReader("scores.txt")
            While Not reader.EndOfStream
                Dim line As String = reader.ReadLine()
                total += Integer.Parse(line)
            End While
        End Using
        Console.WriteLine(total)
    End Sub
End Module

False selects overwrite rather than append. Using disposes the stream when its block ends, including when an exception occurs. Closing the writer before opening the reader ensures buffered output has been written. The EndOfStream test occurs before ReadLine, so it does not try to parse an absent line. The output is 15; a line containing 0 is valid data and does not end the loop.

For structured text, split a line into fields, then validate and convert each field. Merely splitting does not make malformed data valid.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account