Home
VB.NET
File.ReadAllText, Get String From File
Updated Mar 24, 2022
Dot Net Perls
File.ReadAllText. This function reads an entire text file. It returns a String. We store this data into a String dim in our VB.NET program.
System.IO. File.ReadAllText is found in the System.IO namespace. As with all file handling Functions, we must be alert to possible exceptions.
File
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.
Path
Detail The String data returned by the File.ReadAllText function is stored in the Dim value. We get a string from a file.
Finally The String data is printed to the screen with the Console.WriteLine subroutine.
Console.WriteLine
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 Module
File 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.
StreamReader
StreamReader ReadToEnd
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).
Home
Changes
© 2007-2025 Sam Allen