VB.NET File Handling

VB.NET File

File: conceptual illustration

Files are written and read in VB.NET. With the File type in the .NET Framework, you can perform efficient and simple manipulations of files, including reads, writes, and appends. The System.IO namespace—accessed with Imports System.IO—deals with files.

These VB examples show how to handle files. They use System.IO.

File.ReadAllText

Reading an entire text file into a String variable is easy in VB.NET: you can simply call File.ReadAllText. Please note that File.ReadAllText is actually implemented in terms of the other methods in the System.IO namespace. You could implement such a function with StreamReader.

File.ReadAllText
Example directive for System.IO

Imports System.IO

' Remaining program.
' ... End.

Program that handles file [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

Results
    It prints the length of the file at the location in characters.

Overview

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

Note

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 path. Microsoft: "Appends the specified string to the file, creating the file if it doesn't already exist."

File.ReadAllLines

Here, we look at how you can invoke the File.ReadAllLines shared method in the VB.NET programming language. 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. Then, a For Each loop is used on that String(), providing each line in the file for usage elsewhere in code.

Program that uses File.ReadAllLines method [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

StreamReader/StreamWriter

In the VB.NET programming language, the StreamReader type is ideal for looping over the lines in a file. This can also result in less memory usage than storing the entire file into an array and then looping over that. To use the StreamReader, it is best to use the Using statement, which provides for system-level cleanup of resources. One way to use the ReadLine method in a loop is to use the Do While (True) loop construct with an early exit.

StreamReader StreamWriter
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
    Each line in the file will be printed.

Read file into List(Of String)

List type.

Often when using the VB.NET language, 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 the File.ReadAllLines method into a List type using the ToList extension method. Then, you can use each line of the file in a List collection.

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
    The number of lines in the file.

Get line count

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. A more efficient way of doing this would be use the 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
    The number of lines in the file.

File.WriteAllLines

It is possible to take a String() array in the VB.NET programming language and write it as lines to a file. To do this, please use the File.WriteAllLines shared method. In this example, the output file is located in the same directory as the executable and it will contain three lines with the strings "cat", "dog" and "arrow" on it.

Program that writes array to text file [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

Output
    The output file will contain the three lines:
    cat
    dog
    arrow

File size

It is often necessary to get the size of a file in bytes. The FileInfo type is often needed for this purpose, as we demonstrate here.

File Size: FileInfo Example

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 in the VB.NET language to specify and determine volumes, folders and file extensions.

Path Tips File Extension Recursive File Directory Function

Images

Image formats are complex, and 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 Width and Height

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 in the VB.NET language, you can read and write XML in an efficient way.

XmlReader XmlWriter

BinaryReader/BinaryWriter

Square abstract illustration

Computers understand binary data well, but humans don't read it as easily. You can use the BinaryReader and BinaryWriter types to effectively load in binary data into your VB.NET program.

BinaryReader BinaryWriter

Network file downloads

It is possible to use the VB.NET environment to download files from the Internet and process them on your local computer. You can even write the downloaded data to your local disk. Look into the WebClient type.

WebClient

Office

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

Excel Word

Summary

The VB.NET programming language

We looked at how the VB.NET programming language can 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. The VB.NET programming language uses the same .NET input/output libraries as the C# language, and these powerful facilities result in an efficient and terse file handling framework.

.NET