Skip to content
LumenaryAcademy
Practice 60 min

Files, text and asynchronous code

Paths, files and folders with System.IO, CSV and culture-aware formatting, and Async and Await for input and output that does not block.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

The program meets the outside world

Almost every business program written in Visual Basic reads or writes files: the nightly export from a till, a price list from a supplier, a log of what happened, a report for the accountant. That work has three recurring difficulties. Files live at paths that differ between computers and operating systems. Text crosses borders: the number a German spreadsheet writes as 1.250,50 is the number an American one writes as 1,250.50, and a program that ignores this will read one of them wrongly. And input and output are slow compared with computation, so a program that waits for a disk or a network in the wrong place freezes its window or wastes its threads.

This lesson takes them in turn: the System.IO types for paths, files and folders; parsing and formatting text, with Visual Basic's own TextFieldParser for CSV; and asynchronous file code with Async and Await, which you met briefly in the procedures lesson. Every program here works inside a fresh folder in the system's temporary directory and deletes it at the end, a habit worth keeping in your own experiments.

Worked examplesH

Paths, files and folders

The types live in System.IO. Path builds and takes apart paths, File reads and writes whole files in one call, Directory and DirectoryInfo work with folders, and StreamReader and StreamWriter read and write a file piece by piece.

vb
Option Strict On

Imports System.IO
Imports System.Text

Module Program
    Sub Main()
        ' Work only inside a fresh folder in the system's temporary directory.
        Dim folder As DirectoryInfo = Directory.CreateTempSubdirectory("vb-files-")
        Try
            Dim notes As String = Path.Combine(folder.FullName, "harvest-notes.txt")

            ' Write all lines at once, then add to the end.
            File.WriteAllLines(notes, {"Monday: picked 42 kg", "Tuesday: rain, no picking"})
            File.AppendAllText(notes, "Wednesday: picked 57 kg" & Environment.NewLine)

            ' Read everything back.
            Dim lines As String() = File.ReadAllLines(notes)
            Console.WriteLine($"{Path.GetFileName(notes)} has {lines.Length} lines; the last is ""{lines.Last()}""")

            ' File.ReadLines reads lazily, one line at a time, so it suits large files and LINQ.
            Dim picked = Aggregate line In File.ReadLines(notes)
                         Where line.Contains("picked")
                         Into Sum(Integer.Parse(line.Split(" "c)(2)))
            Console.WriteLine($"total picked: {picked} kg")

            ' A StreamWriter in a Using block: the file is flushed and closed even if something fails.
            Dim csvPath As String = Path.Combine(folder.FullName, "prices.csv")
            Using writer As New StreamWriter(csvPath, append:=False, encoding:=New UTF8Encoding(False))
                writer.WriteLine("crop,price_per_kg")
                writer.WriteLine("coffee,3.20")
                writer.WriteLine("tea,1.85")
            End Using

            ' Paths are taken apart with Path, never by hand.
            Console.WriteLine($"{Path.GetFileNameWithoutExtension(csvPath)} | {Path.GetExtension(csvPath)} | {Path.GetFileName(Path.ChangeExtension(csvPath, ".bak"))}")

            ' Directories and file information.
            For Each file In folder.EnumerateFiles("*.*").OrderBy(Function(f) f.Name)
                Console.WriteLine($"{file.Name,-18} {file.Length,4} bytes")
            Next
            Console.WriteLine($"exists? {File.Exists(csvPath)}; missing? {Not File.Exists(Path.Combine(folder.FullName, "nope.txt"))}")
        Finally
            folder.Delete(recursive:=True)        ' leave nothing behind
        End Try
        Console.WriteLine($"folder still there? {folder.Exists}")
    End Sub
End Module

On Linux it printed:

text
harvest-notes.txt has 3 lines; the last is "Wednesday: picked 57 kg"
total picked: 99 kg
prices | .csv | prices.bak
harvest-notes.txt    71 bytes
prices.csv           39 bytes
exists? True; missing? True
folder still there? False
  • A temporary folder of your own. Directory.CreateTempSubdirectory (.NET 7 and later) creates a new, uniquely named folder in the system's temporary directory, and the Finally block deletes it with everything inside, however the Try block ends.
  • Path.Combine joins folder and file names with the right separator for the operating system (\ on Windows, / elsewhere). Never build paths by concatenating strings with "\": that is the most common reason old Visual Basic code fails on Linux and macOS. Path.GetFileName, GetFileNameWithoutExtension, GetExtension and ChangeExtension take paths apart without string surgery.
  • Whole-file calls. File.WriteAllLines, File.AppendAllText and File.ReadAllLines open, transfer and close in one statement. They are ideal for small files. For a large log, File.ReadAllLines loads every line into memory; File.ReadLines reads lazily, one line at a time, so it can feed a LINQ query, here an Aggregate from the previous lesson, without holding the file in memory.
  • Streams in Using blocks. A StreamWriter holds the file open until it is disposed; the Using block guarantees that it is flushed and closed. New UTF8Encoding(False) writes UTF-8 without a byte-order mark, which most other tools prefer.
  • Line endings. The notes file is 71 bytes because each of its three lines ends with one character, vbLf, on Linux; on Windows, Environment.NewLine and WriteAllLines use the two characters vbCrLf, and the same file is 74 bytes. Code that splits text on vbCrLf breaks on files from Linux, and the reverse; File.ReadAllLines and ReadLine accept both.
DefinitionsH

Formatting text for people

Definition— Culture

A culture (System.Globalization.CultureInfo) bundles the conventions of a language and region: the decimal and thousands separators, the currency symbol and its position, date formats, month names and sorting rules. Every thread has a current culture, normally taken from the operating system's settings. The invariant culture is a fixed, culture-neutral set of conventions, based on English, for data that programs read.

Interpolated strings, ToString, String.Format and the conversion functions such as CDbl all use the current culture unless you pass another one. That is right for text shown to the person at the keyboard, and wrong for files that other programs read.

vb
Option Strict On

Imports System.Globalization

Module Program
    Sub Main()
        Dim price As Decimal = 1234567.891D

        ' Interpolated strings and ToString use the *current* culture unless told otherwise.
        CultureInfo.CurrentCulture = New CultureInfo("de-DE")
        Console.WriteLine($"current culture de-DE: {price:N2}")
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture
        Console.WriteLine($"invariant culture:     {price:N2}")

        ' The same value for readers in different places.
        For Each name In {"en-US", "fr-FR", "hi-IN", "ja-JP", "pt-BR"}
            Dim culture As New CultureInfo(name)
            Console.WriteLine($"{name}  {price.ToString("N2", culture),16}  {price.ToString("C", culture)}")
        Next

        ' Format items: {index,alignment:format}
        Console.WriteLine(String.Format("[{0,8:F3}] [{1,-6}] [{2:D5}] [{3:P1}] [{4:X4}] [{5:E2}]",
                                        Math.PI, "left", 42, 0.256, 255, 6.02214076E+23))

        ' Dates: a fixed pattern for files and logs, the culture's own long form for people.
        Dim sentAt As New DateTime(2026, 11, 19, 14, 5, 0)
        Console.WriteLine(sentAt.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture))
        Console.WriteLine(sentAt.ToString("D", New CultureInfo("es-MX")))
        Console.WriteLine(sentAt.ToString("o", CultureInfo.InvariantCulture))   ' round-trip format

        ' Parsing must name the culture too: the same text means different numbers.
        Dim text As String = "1.250"
        Console.WriteLine($"""{text}"" in en-US = {Decimal.Parse(text, New CultureInfo("en-US"))}, in de-DE = {Decimal.Parse(text, New CultureInfo("de-DE"))}")
    End Sub
End Module

It printed:

text
current culture de-DE: 1.234.567,89
invariant culture:     1,234,567.89
en-US      1,234,567.89  $1,234,567.89
fr-FR      1 234 567,89  1 234 567,89 €
hi-IN      12,34,567.89  ₹12,34,567.89
ja-JP      1,234,567.89  ¥1,234,568
pt-BR      1.234.567,89  R$ 1.234.567,89
[   3.142] [left  ] [00042] [25.6 %] [00FF] [6.02E+023]
2026-11-19 14:05
jueves, 19 de noviembre de 2026
2026-11-19T14:05:00.0000000
"1.250" in en-US = 1.250, in de-DE = 1250
  • The current culture changes interpolation. The same {price:N2} printed 1.234.567,89 under de-DE and 1,234,567.89 under the invariant culture. A program that writes a CSV file with {price} produces a different file on a German computer.
  • Cultures differ in more than separators. French groups digits with a narrow no-break space (the gaps above are that character, not ordinary spaces) and puts the euro sign after the number; Indian English groups by lakh and crore (12,34,567.89); the Japanese currency format rounds to whole yen and uses a full-width yen sign. The exact output comes from the culture data of the operating system (ICU on Linux and macOS), so details can vary slightly between systems.
  • Format items have the shape {index,alignment:format}. A positive alignment right-aligns in that many characters, a negative one left-aligns; F3 is fixed-point with three decimals, D5 pads an integer with zeros, P1 is a percentage, X4 hexadecimal and E2 scientific notation. Interpolated strings use the same {value,alignment:format} syntax.
  • Dates. Use a fixed pattern such as yyyy-MM-dd HH:mm, or the round-trip format o, for files and logs; use a culture's own patterns, such as D for the long date, for people.
  • Parsing needs a culture too. The text 1.250 is one and a quarter in en-US and one thousand two hundred and fifty in de-DE. (The Decimal kept the three decimal places it was given, so it printed as 1.250.)

The rule professionals follow: invariant culture for data, current culture for people. Programs that write data files, like the rest of this lesson's examples, often set CultureInfo.CurrentCulture = CultureInfo.InvariantCulture at the start of Sub Main so that every number they print is predictable, and pass a culture explicitly wherever they format text for a human.

Worked examplesH

Reading CSV safely

CSV looks simple until a field contains a comma. The standard convention puts such fields in double quotes, and a naive Split(","c) then breaks them in two. Visual Basic's own library, Microsoft.VisualBasic.FileIO, has a parser that handles quoting, which C# programmers often borrow from it:

vb
Option Strict On

Imports System.Globalization
Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Module Program
    Sub Main()
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture     ' the same output on every computer

        ' An export with a quoted field containing a comma, an empty line and a mistyped number.
        Dim export As String = "supplier,city,amount
""Moyo & Sons, Ltd"",Bulawayo,1250.50
Tanaka Shoten,Osaka,980

Ferreira Lda,Porto,12O.00"

        ' A naive Split breaks the quoted field in two.
        Dim secondLine As String = export.Split(ControlChars.Lf)(1)
        Console.WriteLine($"Split(',') sees {secondLine.Split(","c).Length} fields in: {secondLine}")

        ' TextFieldParser (from Microsoft.VisualBasic.FileIO) understands quotes and skips blank lines.
        Dim total As Decimal = 0D
        Using parser As New TextFieldParser(New StringReader(export))
            parser.TextFieldType = FieldType.Delimited
            parser.SetDelimiters(",")
            parser.HasFieldsEnclosedInQuotes = True
            parser.ReadLine()                                   ' skip the header
            Do Until parser.EndOfData
                Dim fields As String() = parser.ReadFields()
                Dim amount As Decimal
                If Decimal.TryParse(fields(2), NumberStyles.Number, CultureInfo.InvariantCulture, amount) Then
                    Console.WriteLine($"{fields(0),-18}{fields(1),-10}{amount,10:N2}")
                    total += amount
                Else
                    Console.WriteLine($"{fields(0)}: '{fields(2)}' is not a number, skipped")
                End If
            Loop
        End Using
        Console.WriteLine($"{"total",-28}{total,10:N2}")
    End Sub
End Module

It printed:

text
Split(',') sees 4 fields in: "Moyo & Sons, Ltd",Bulawayo,1250.50
Moyo & Sons, Ltd  Bulawayo    1,250.50
Tanaka Shoten     Osaka         980.00
Ferreira Lda: '12O.00' is not a number, skipped
total                         2,230.50
  • Split miscounted the fields of "Moyo & Sons, Ltd",Bulawayo,1250.50 as four, because it cannot know that the first comma is inside quotes.
  • TextFieldParser read the same line as three fields, removed the quotes, and skipped the blank line. ReadFields returns one record's fields as an array; EndOfData says when the input is exhausted. It reads from any TextReader: here a StringReader over a string, in real code a StreamReader or a file name. It also reads fixed-width files, common in exports from older mainframe and accounting systems, when TextFieldType is FixedWidth.
  • Decimal.TryParse with CultureInfo.InvariantCulture reads the amounts the same way on every computer, and reports 12O.00 (with a letter O) as invalid instead of crashing, so the program can skip or report the record and carry on.

For large or demanding CSV work, many teams use an open-source library from NuGet instead, which adds mapping to classes and better performance. TextFieldParser remains a solid, dependency-free choice that ships with every Visual Basic project.

ComputationC

Asynchronous files

Reading a file means waiting for a disk, and on a server or a network share the wait can be long. In a Windows Forms or WPF application, waiting on the user-interface thread freezes the window; in a server, a thread blocked on input and output cannot serve anyone else. The Async versions of the file methods return a Task that completes when the operation does, and Await lets the procedure step aside until then. This program writes three files at once, reads each line by line, cancels a slow job and handles a missing file:

vb
Option Strict On

Imports System.Globalization
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Program
    ' Write one weather station's readings to its own file.
    Async Function SaveStationAsync(folder As String, station As String, readings As Double()) As Task(Of String)
        Dim filePath As String = Path.Combine(folder, station & ".txt")
        Await File.WriteAllLinesAsync(filePath, readings.Select(Function(r) r.ToString("F1")))
        Return filePath
    End Function

    ' Read a file line by line, awaiting each line instead of blocking the thread.
    Async Function MaxReadingAsync(filePath As String) As Task(Of Double)
        Dim best As Double = Double.MinValue
        Using reader As New StreamReader(filePath)
            Dim line As String = Await reader.ReadLineAsync()
            While line IsNot Nothing
                best = Math.Max(best, Double.Parse(line))
                line = Await reader.ReadLineAsync()
            End While
        End Using
        Return best
    End Function

    ' A slow job that honours cancellation.
    Async Function SlowSumAsync(token As CancellationToken) As Task(Of Integer)
        Dim total As Integer = 0
        For i As Integer = 1 To 100
            Await Task.Delay(50, token)          ' throws OperationCanceledException once cancelled
            total += i
        Next
        Return total
    End Function

    Async Function RunAsync() As Task
        Dim folder As DirectoryInfo = Directory.CreateTempSubdirectory("vb-async-")
        Try
            Dim data As New Dictionary(Of String, Double()) From {
                {"nairobi", {17.5, 19.2, 21.0}},
                {"quito", {12.1, 14.8, 13.3}},
                {"hanoi", {24.9, 27.4, 26.1}}
            }
            ' Start all three writes, then wait for them all.
            Dim saving As List(Of Task(Of String)) =
                data.Select(Function(kv) SaveStationAsync(folder.FullName, kv.Key, kv.Value)).ToList()
            Dim paths As String() = Await Task.WhenAll(saving)
            Console.WriteLine($"wrote {paths.Length} files")

            For Each p In paths.OrderBy(Function(x) x)
                Console.WriteLine($"{Path.GetFileNameWithoutExtension(p),-8} max {Await MaxReadingAsync(p):F1}")
            Next

            ' Cancellation: give the slow job 200 ms.
            Using cts As New CancellationTokenSource(TimeSpan.FromMilliseconds(200))
                Try
                    Console.WriteLine($"finished: {Await SlowSumAsync(cts.Token)}")
                Catch ex As OperationCanceledException
                    Console.WriteLine("cancelled after 200 ms, as requested")
                End Try
            End Using

            ' An exception inside an awaited task surfaces at the Await.
            Try
                Dim text As String = Await File.ReadAllTextAsync(Path.Combine(folder.FullName, "lima.txt"))
            Catch ex As FileNotFoundException
                Console.WriteLine($"not found: {Path.GetFileName(ex.FileName)}")
            End Try
        Finally
            folder.Delete(recursive:=True)
        End Try
    End Function

    Sub Main()
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture
        RunAsync().GetAwaiter().GetResult()
    End Sub
End Module

It printed:

text
wrote 3 files
hanoi    max 27.4
nairobi  max 21.0
quito    max 14.8
cancelled after 200 ms, as requested
not found: lima.txt
  • Concurrent writes. The Select starts all three SaveStationAsync calls before anything is awaited; Task.WhenAll then waits for all of them and returns their results in the same order. The writes overlap instead of running one after another, the same pattern the procedures lesson used with Task.Delay.
  • Line by line. MaxReadingAsync awaits ReadLineAsync until it returns Nothing at the end of the file. Await is allowed inside a Using block, so the reader is still disposed properly.
  • Await inside an interpolated string works: {Await MaxReadingAsync(p):F1} waits for the result, then formats it.
  • Cancellation is cooperative. A CancellationTokenSource created with a time span cancels its token after that time; methods that accept the token, such as Task.Delay here or File.ReadAllTextAsync, then throw an OperationCanceledException, which the caller catches. Long-running methods of your own should accept a CancellationToken and pass it on.
  • Exceptions travel through Await. The missing file's FileNotFoundException was raised inside a task, and it reappeared at the Await, where an ordinary Try ... Catch handled it.

Where Visual Basic stops

Microsoft's decision to stop evolving Visual Basic is visible here. Two features that C# gained after 2012 never came to Visual Basic:

  • No Await in Catch or Finally. Writing one is compile error BC36943, 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement. If cleanup must be asynchronous, record the exception in a variable inside the Catch, and do the awaiting after the Try block ends.
  • No asynchronous streams. Methods such as File.ReadLinesAsync (.NET 7 and later) return an IAsyncEnumerable(Of String). C# consumes one with await foreach; Visual Basic has no Await For Each, so you drive the enumerator yourself, which is the "consumption-only" support described in the first lesson:
vb
Dim lines = File.ReadLinesAsync(filePath).GetAsyncEnumerator()
While Await lines.MoveNextAsync()
    Console.WriteLine(lines.Current)
End While
Await lines.DisposeAsync()

Library code usually adds .ConfigureAwait(False) to each Await (as in Await reader.ReadLineAsync().ConfigureAwait(False)), so that it does not insist on resuming on the caller's user-interface thread. Application code that updates controls after an Await must not do this, because controls may only be touched from the user-interface thread.

ExplanationH

Files in older Visual Basic code

Code that began life in VB6 or early VB.NET often uses the classic file functions, which Microsoft.VisualBasic still provides on modern .NET:

vb
Dim f As Integer = FreeFile()
FileOpen(f, logPath, OpenMode.Output)
PrintLine(f, "first line")
FileClose(f)

f = FreeFile()
FileOpen(f, logPath, OpenMode.Input)
Do Until EOF(f)
    Console.WriteLine(LineInput(f))
Loop
FileClose(f)

A program using exactly these calls compiled and ran on .NET 10 for this lesson, writing and reading back its two lines. The style works, but file numbers are global state, a forgotten FileClose leaves the file locked, and errors are easy to lose. When you maintain such code, convert it to File, StreamReader and StreamWriter with Using blocks, one routine at a time.

Other things to look for when maintaining file code:

  • Hard-coded paths such as "C:\Data\export.csv" or App.Path & "\settings.ini". Replace them with configuration and Path.Combine, and with Environment.GetFolderPath for standard folders such as the user's documents.
  • Old encodings. VB6-era files are usually in a Windows code page such as 1252, not UTF-8. On modern .NET, Encoding.GetEncoding(1252) throws NotSupportedException until you call Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) once at start-up; after that, pass the encoding to StreamReader or File.ReadAllText. Reading such a file as UTF-8 turns every accented letter into a replacement character.
  • My.Computer.FileSystem. The My namespace offers convenient file helpers in Windows Forms projects, but a modern console project does not include My.Computer; code using it fails to compile with error BC30456, 'Computer' is not a member of 'app.My' (for a project named app). The System.IO equivalents work everywhere.
  • Writing in place. Programs that overwrite an important file directly can leave it half-written if they crash. The safer pattern is to write a temporary file in the same folder and then replace the original with File.Move(temp, target, overwrite:=True) or File.Replace.
Common misconceptionsH

Common misconceptions

Misconception

"Async makes code run in parallel." Async and Await let a procedure wait without blocking a thread. Work runs concurrently only if you start several operations before awaiting them, as with Task.WhenAll; awaiting each call in turn runs them one after another. For CPU-heavy work in parallel, use Parallel.For or Task.Run.

Misconception

"Numbers in a file can be read with CDbl." CDbl and Double.Parse without a culture use the current culture, so a file written in one country may be misread in another. Read and write data with CultureInfo.InvariantCulture.

Misconception

"A CSV line can be split on commas." Quoted fields may contain commas, quotes and even line breaks. Use TextFieldParser or a CSV library.

Exercises

Exercises

1. Files, text and asynchronous code

Warm-upComputational

What does this line print?

Console.WriteLine(Path.GetFileName(Path.ChangeExtension(Path.Combine("reports", "march.csv"), ".xlsx")))

2. Files, text and asynchronous code

CoreComputational

What does this print?

Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:D4}|{1:N0}|{2:F2}", 42, 1234567, 2.5))

3. Files, text and asynchronous code

CoreComputational

What does this print?

Console.WriteLine($"{Decimal.Parse("2,5", New CultureInfo("de-DE"))} {Decimal.Parse("2,5", New CultureInfo("en-US"))}")

(The program's current culture is the invariant culture.)

Choose one

4. Files, text and asynchronous code

CoreComputational

A TextFieldParser with SetDelimiters(",") and HasFieldsEnclosedInQuotes = True reads this line:

"Kigali, Rwanda",2026,"say ""hi"""

How many fields does ReadFields() return?

5. Files, text and asynchronous code

CoreComputational

With p the path of a new file in a temporary folder, what does this print?

File.WriteAllLines(p, {"a", "b"})
File.AppendAllText(p, "c")
File.AppendAllText(p, "d" & vbLf)
Dim lines = File.ReadAllLines(p)
Console.WriteLine($"{lines.Length} {lines.Last()}")

6. Files, text and asynchronous code

CoreHuman

Inside an Async Function, roughly how long does each fragment take?

' A
Await Task.Delay(300)
Await Task.Delay(300)

' B
Await Task.WhenAll(Task.Delay(300), Task.Delay(300))
Choose one

7. Files, text and asynchronous code

StretchHuman

You want to delete a temporary file asynchronously whether or not an operation fails. Which approach compiles in Visual Basic?

Choose one

Further reading and resources