File.ReadAllText, Get String From File
This page was last reviewed on 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.
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.
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.
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 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 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).
© 2007-2024 Sam Allen.