VB.NET File

Array Class Collections File String Cast Console Data Directive Enum Exception If Interface Lambda LINQ Loop Nothing Number Process Property Regex Select Sort StringBuilder Structure Sub Time Windows

File

A form of persistent storage,
files are written
and read. With the File type, we perform efficient and simple manipulations of files, including reads, writes and appends. The System.IO namespace deals with files.

StreamReader

Some approaches to file handling are complex. The StreamReader type is a simple way to read files. So let us use it instead. We often employ a using-construct to create a StreamReader object.

Tip:The StreamReader type is ideal for looping over the lines in a file. This can also result in less memory usage.

Using keyword

Using:To use the StreamReader, it is best to use the Using statement, which provides for system-level cleanup of resources.

While:One way to use the ReadLine method in a loop is to use the Do While (True) loop construct with an early exit.

StreamReaderStreamWriter
Based on:

.NET 4.5

Program that uses StreamReader type: VB.NET

Imports System.IO

Module Module1

    Sub Main()
	' Create StreamReader for the file.
	Using reader As StreamReader = New StreamReader("file.txt")
	    ' Do While true loop.
	    Do While (True)
		' Read a line.
		Dim line As String = reader.ReadLine
		' See if line is Nothing.
		If line Is Nothing Then
		    Exit Do
		End If
		' Write line to screen.
		Console.WriteLine(line)
	    Loop
	End Using
    End Sub

End Module

Output: requires file

Line 1
Line 2

Output:When executed, each line in the file will be printed. You may need to change to change the file name to a location that exists.

ReadAllText

String

Reading an entire text file into a String variable is easy in VB.NET. We simply call File.ReadAllText. Please note that this function is actually implemented in terms of the other methods in the System.IO namespace.

Tip:You could implement a function equivalent to ReadAllText with the StreamReader type.

File.ReadAllText
Program that uses ReadAllText: VB.NET

Imports System.IO

Module Module1
    Sub Main()
	Dim value As String = File.ReadAllText("C:\file.txt")
	Console.WriteLine(value.Length)
    End Sub
End Module

Output: depends on file

40

Overview

Squares

We describe in brief many of the functions available in the VB.NET language and .NET Framework on the File type. Some have been omitted. The System.IO namespace provides many other types that are separate from these shared methods.

File.ReadAllBytes:Useful for files not stored as plain text.
You can open images or movies with this method.

File.ReadAllLines:Microsoft: "Opens a file, reads all lines of the file with the specified encoding, and closes the file."

File.ReadAllText:Returns the contents of the text file at the specified path as a string. Useful for plain text or settings files.

File.WriteAllBytes:Useful for files such as images that were created or mutated in memory.

File.WriteAllLines:Stores a string array in the specified file, overwriting the contents. Shown in an example below.

File.WriteAllText:Writes the contents of a string to a text file. One of the simplest ways to persist text data.

File.AppendAllText:Use to append the contents string to the file at the path. It creates a new file if needed.

ReadAllLines

Foreach loop construct

Here, we look at how you can invoke the File.ReadAllLines shared method. First, the program calls the ReadAllLines method with an argument equal to the file name. Then the result of the method is stored in the String array variable.

Next:A For-Each loop is used on that String, providing each line in the file for usage elsewhere in code.

File.ReadLines:ReadLines is different from ReadAllLines.
It reads one line in at a time.
This uses less memory.

File.ReadLines
Program that uses ReadAllLines: VB.NET

Imports System.IO

Module Module1

    Sub Main()
	' Read the file into an array.
	' ... Make sure to create the required file if isn't there.
	Dim array As String() = File.ReadAllLines("file.txt")
	Dim line As String
	For Each line In array
	    ' We now have the line so can use it.
	    Dim length As Integer = line.Length
	Next
    End Sub

End Module

List

List type

Often you will want to store collections of strings in the form of List types. However, the File.ReadAllLines method returns a String array. You can convert the result of File.ReadAllLines into a List type using the ToList extension.

Then:You can use each line of the file in a List collection.
You can apply all List functions.

List
Program that uses ToList method on file array: VB.NET

Imports System.IO

Module Module1

    Sub Main()
	' Create a list reference variable.
	' ... Then read all lines in the file and convert the array to a List.
	Dim list As List(Of String) = File.ReadAllLines("file.txt").ToList
	Console.WriteLine(list.Count)
    End Sub

End Module

Output: depends on file

5

Line count

Length property

There are a variety of ways you can use to acquire the line count of a file. In this example, we see that you can actually load the file into an array, and then get the Length of that array.

Tip:You could instead use StreamReader code above, and then increment an integer on each successful call to the ReadLine method.

Program that gets line count: VB.NET

Imports System.IO

Module Module1

    Sub Main()
	' Get the length of the file.
	' ... Not the fastest way to get the line count.
	Dim length As Integer = File.ReadAllLines("file.txt").Length
	Console.WriteLine(length)
    End Sub

End Module

Output: depends on file

5

WriteAllLines

Array type

It is possible to take a String array and write it as lines to a file. Please use the File.WriteAllLines shared method. In this example, the output file will contain three lines with the strings "cat", "dog" and "arrow" on it.

Program that uses WriteAllLines: VB.NET

Imports System.IO

Module Module1

    Sub Main()
	' Create an array of three elements.
	Dim array As String() = New String() {"cat", "dog", "arrow"}
	' Write the array to a file.
	File.WriteAllLines("file.txt", array)
    End Sub

End Module

File contents: file.txt

cat
dog
arrow

Paths

Path type

Files found in external storage such as hard disks, network servers, and CDs or DVDs all have file paths. You can use the Path type to specify and determine volumes, folders and file extensions.

PathFile Extension

Recursive:Newer versions of the .NET Framework include a method that handles recursive directory file lists. We show an older solution.

Recursive Files

Operations

Note

Many operations are available in the System.IO namespace. A file may be copied. A file info may be received, allowing you to check sizes and dates without using the actual file. We explore these operating system calls.

File.CopyFile.ExistsDirectory, package

FileInfo:It is often necessary to get the size of a file in bytes. The FileInfo type is often needed for this purpose.

File Size

Download files. With WebClient, we use the VB.NET environment to download files from the Internet. We process them on the local computer. We even write the downloaded data to the local disk.

WebClient

Images

Image

Image formats are complex. It is probably best to avoid processing them yourself. With the Image type and its properties, you can read JPG, PNG and other types of files in your VB.NET program with a minimum of effort.

Image

XML

Extensible markup language: XML

Data is usually best stored in a structured format. In cases where a database is not necessary, you can use XML files. With XmlReader and XmlWriter you can read and write XML in an efficient way.

XmlReaderXmlWriter

BinaryReader

Abstract squares

Computers understand binary data well. But humans don't read it with the same ease. You can use the BinaryReader and BinaryWriter types to effectively load in binary data. These types are fast and easy-to-use.

BinaryReaderBinaryWriter

Tip:These two types are often used together. It is easy to read (with BinaryReader) a file you write (with BinaryWriter).

Compress

Compression

Files can be compressed in the VB.NET language. This requires a newer version of the .NET Framework that includes the System.IO.Compression namespace. We show how to handle compressed files.

Compress

ZipFile:This class can be used to compress an entire directory. We can avoid writing the code ourselves.

ZipFile

Office

Sometimes, you may need to read data from an Excel spreadsheet or Word DOC into your VB.NET program. Office formats are complex. These articles introduce ways to read in these files.

Excel:This Excel tutorial reads in sheets from XLS and XLSX files. Performance is important here.

Excel

Word:This simple Word tutorial parses text from a Word document. The code is somewhat confusing.

Word

Summary

The VB.NET programming language

With clear code,
such as the Using statement,
we read
and write (mutate) files. In particular we focused on text files. But these methods can also act upon more varied file types such as images or binary data.

VB.NET