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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 24, 2022 (rewrite).