Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Files and Databases

Text Files and Streams

Learn VB.NET file handling - File.ReadAllText, StreamReader and StreamWriter, Path and Directory, Using blocks, encodings, CSV parsing, My.Computer.FileSystem and error handling, with runnable C# stand-ins.

Programs that forget everything when they close are toys. To keep data you write it to files, and to use data from elsewhere you read files. .NET models files through two layers: static helpers for the simple cases (File.ReadAllText) and streams for large or incremental work (StreamReader, StreamWriter).

The VB.NET compiler is not available here, so VB is read-only. The runnable blocks are C# stand-ins that call the same System.IO types in a temporary folder and clean up after themselves.

Whole-file helpers

For small files the one-line helpers are perfect:

VB
Imports System.IO

File.WriteAllText("notes.txt", "first line" & vbCrLf & "second line")
Dim text As String = File.ReadAllText("notes.txt")
Dim lines As String() = File.ReadAllLines("notes.txt")
File.AppendAllText("notes.txt", vbCrLf & "third line")

If File.Exists("notes.txt") Then File.Delete("notes.txt")

ReadAllLines returns an array; File.ReadLines returns a lazy sequence, which is better for big files because it reads one line at a time. WriteAllText replaces the file; AppendAllText adds to the end.

C# Write, append and read (C# stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Streams, StreamReader and StreamWriter

A stream is a flow of bytes. StreamReader and StreamWriter wrap a stream with text decoding (UTF-8 by default). You process a big file line by line without ever holding it all in memory:

VB
Using reader As New StreamReader("big.log")
    Dim line As String = reader.ReadLine()
    While line IsNot Nothing
        If line.Contains("ERROR") Then Console.WriteLine(line)
        line = reader.ReadLine()
    End While
End Using

Using writer As New StreamWriter("out.txt", append:=False)
    writer.WriteLine("Name,Score")
    writer.WriteLine("Ada,90")
End Using

Using: always close what you open

File handles are scarce operating-system resources. A Using block guarantees Dispose runs, even if an exception is thrown, which closes the file and flushes buffered text. Forgetting it can leave data unwritten and the file locked.

C# Using, StreamWriter and StreamReader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Paths and folders

Never join paths with & and a backslash. Path.Combine uses the right separator for the platform, and Path.GetFileName, GetExtension, GetDirectoryName and ChangeExtension take paths apart. Directory.GetFiles(folder, "*.txt"), Directory.CreateDirectory and Directory.EnumerateFiles handle folders, and Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) finds well-known locations.

C# Taking paths apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The VB shortcut: My.Computer.FileSystem

VB has a convenience namespace: My.Computer.FileSystem.ReadAllText(path), WriteAllText(path, text, append), CopyFile, MoveFile, DeleteFile, GetFiles. It wraps the same classes, and is only available in VB. Code that uses plain System.IO can be moved to C# unchanged, so prefer it in new code.

Parsing a simple CSV

A real CSV needs a proper parser (quoted fields, embedded commas), but a simple, comma-only file can be split by hand:

VB
For Each line In File.ReadLines("scores.csv").Skip(1)
    Dim parts = line.Split(","c)
    Dim score = Integer.Parse(parts(1))
Next

For quoted fields use Microsoft.VisualBasic.FileIO.TextFieldParser (VB only) or a CSV library.

C# Simple CSV to objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Errors you must expect

Files are an outside world. Catch the specific exceptions: FileNotFoundException, DirectoryNotFoundException, UnauthorizedAccessException (permissions), IOException (locked file, disk full). Do not check File.Exists and assume the next line is safe; the file can disappear in between. Catch around the operation.

VB
Try
    Dim text = File.ReadAllText(path)
Catch ex As FileNotFoundException
    MessageBox.Show("That file does not exist.")
Catch ex As IOException
    MessageBox.Show("The file is in use: " & ex.Message)
End Try

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does File.WriteAllText do if the file already exists?

    WriteAllText overwrites; AppendAllText adds to the end.
  2. 2. Why use a Using block with StreamReader?

    Using calls Dispose, which closes the handle and flushes buffers.
  3. 3. Which is the best way to build a file path?

    Path.Combine uses the correct separator for the platform.
  4. 4. Which method reads a huge file lazily, line by line?

    ReadLines returns a lazily evaluated sequence of lines.

Summary

  • File helpers suit small files; StreamReader/StreamWriter suit big or incremental work.
  • Wrap streams in Using so they are always closed.
  • Build paths with Path.Combine and take them apart with Path.Get....
  • Catch specific I/O exceptions around the operation itself.

Next: JSON and XML Serialization