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.
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.
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 ModuleOn Linux it printed:
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 theFinallyblock deletes it with everything inside, however theTryblock ends. Path.Combinejoins 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,GetExtensionandChangeExtensiontake paths apart without string surgery.- Whole-file calls.
File.WriteAllLines,File.AppendAllTextandFile.ReadAllLinesopen, transfer and close in one statement. They are ideal for small files. For a large log,File.ReadAllLinesloads every line into memory;File.ReadLinesreads lazily, one line at a time, so it can feed a LINQ query, here anAggregatefrom the previous lesson, without holding the file in memory. - Streams in
Usingblocks. AStreamWriterholds the file open until it is disposed; theUsingblock 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.NewLineandWriteAllLinesuse the two charactersvbCrLf, and the same file is 74 bytes. Code that splits text onvbCrLfbreaks on files from Linux, and the reverse;File.ReadAllLinesandReadLineaccept both.
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.
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 ModuleIt printed:
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}printed1.234.567,89underde-DEand1,234,567.89under 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;F3is fixed-point with three decimals,D5pads an integer with zeros,P1is a percentage,X4hexadecimal andE2scientific 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 formato, for files and logs; use a culture's own patterns, such asDfor the long date, for people. - Parsing needs a culture too. The text
1.250is one and a quarter inen-USand one thousand two hundred and fifty inde-DE. (TheDecimalkept the three decimal places it was given, so it printed as1.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.
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:
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 ModuleIt printed:
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.50Splitmiscounted the fields of"Moyo & Sons, Ltd",Bulawayo,1250.50as four, because it cannot know that the first comma is inside quotes.TextFieldParserread the same line as three fields, removed the quotes, and skipped the blank line.ReadFieldsreturns one record's fields as an array;EndOfDatasays when the input is exhausted. It reads from anyTextReader: here aStringReaderover a string, in real code aStreamReaderor a file name. It also reads fixed-width files, common in exports from older mainframe and accounting systems, whenTextFieldTypeisFixedWidth.Decimal.TryParsewithCultureInfo.InvariantCulturereads the amounts the same way on every computer, and reports12O.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.
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:
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 ModuleIt printed:
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
Selectstarts all threeSaveStationAsynccalls before anything is awaited;Task.WhenAllthen 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 withTask.Delay. - Line by line.
MaxReadingAsyncawaitsReadLineAsyncuntil it returnsNothingat the end of the file.Awaitis allowed inside aUsingblock, so the reader is still disposed properly. Awaitinside an interpolated string works:{Await MaxReadingAsync(p):F1}waits for the result, then formats it.- Cancellation is cooperative. A
CancellationTokenSourcecreated with a time span cancels its token after that time; methods that accept the token, such asTask.Delayhere orFile.ReadAllTextAsync, then throw anOperationCanceledException, which the caller catches. Long-running methods of your own should accept aCancellationTokenand pass it on. - Exceptions travel through
Await. The missing file'sFileNotFoundExceptionwas raised inside a task, and it reappeared at theAwait, where an ordinaryTry ... Catchhandled 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
AwaitinCatchorFinally. 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 theCatch, and do the awaiting after theTryblock ends. - No asynchronous streams. Methods such as
File.ReadLinesAsync(.NET 7 and later) return anIAsyncEnumerable(Of String). C# consumes one withawait foreach; Visual Basic has noAwait For Each, so you drive the enumerator yourself, which is the "consumption-only" support described in the first lesson:
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.
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:
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"orApp.Path & "\settings.ini". Replace them with configuration andPath.Combine, and withEnvironment.GetFolderPathfor 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)throwsNotSupportedExceptionuntil you callEncoding.RegisterProvider(CodePagesEncodingProvider.Instance)once at start-up; after that, pass the encoding toStreamReaderorFile.ReadAllText. Reading such a file as UTF-8 turns every accented letter into a replacement character. My.Computer.FileSystem. TheMynamespace offers convenient file helpers in Windows Forms projects, but a modern console project does not includeMy.Computer; code using it fails to compile with error BC30456, 'Computer' is not a member of 'app.My' (for a project namedapp). TheSystem.IOequivalents 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)orFile.Replace.
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
1. Files, text and asynchronous code
Warm-upComputationalWhat does this line print?
Console.WriteLine(Path.GetFileName(Path.ChangeExtension(Path.Combine("reports", "march.csv"), ".xlsx")))
2. Files, text and asynchronous code
CoreComputationalWhat 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
CoreComputationalWhat 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.)
4. Files, text and asynchronous code
CoreComputationalA 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
CoreComputationalWith 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
CoreHumanInside 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))
7. Files, text and asynchronous code
StretchHumanYou want to delete a temporary file asynchronously whether or not an operation fails. Which approach compiles in Visual Basic?
Further reading and resources
- File and stream I/O · MicrosoftFiles, directories, paths and streams in .NET.
- TextFieldParser class · MicrosoftThe Visual Basic library's parser for delimited and fixed-width text.
- Standard numeric format strings · MicrosoftEvery format specifier, such as N2, C, P1, D5 and X4.
- Asynchronous programming with Async and Await (Visual Basic) · MicrosoftThe Visual Basic guide to Async, Await and Task.