To start, this program imports the System.IO namespace. In Main, it calls the File.ReadAllText function and passes the String literal "C:\file.txt" as the parameter.
Info For this example to work, that file must exist on the disk. You can change the path if needed.
Imports System.IO
Module Module1
Sub Main()
' Open file and store in String.
Dim value As String = File.ReadAllText("C:\file.txt")
' Write to screen.
Console.WriteLine(value)
End Sub
End ModuleFile contents.
A discussion. What should you do if you want to read in a file line-by-line instead of storing the entire content in a String? The StreamReader type is ideal for this purpose.
And Call ReadLine on StreamReader. This can lead to performance improvements over File.ReadAllText.
A summary. The File.ReadAllText function reads the entire text contents into a String. StreamReader can read files in line-by-line, which is more efficient with large files.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 24, 2022 (rewrite).