VB.NET File.ReadAllText, Get String From FileUse the File.ReadAllText Function from System.IO to get a string from a file.
reads an entire TXT file. We store this data into a String dim in the VB.NET program. This Function is found in the System.IO namespace. As with all file handling Functions, we must be alert to possible exceptions.File
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. For this example to work, that file must exist on the disk.
Then: 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.
VB.NET program that reads in text file
' Open file and store in String.
Dim value As String = File.ReadAllText("C:\file.txt")
' Write to screen.
What should you do if you want to read in a file line-by-line instead of storing the entire thing in a String? The StreamReader type is ideal for this purpose. We can use its ReadLine Function.
Note: You can read a specific article on StreamReader, and also check out more general file handing tips in the VB.NET language.StreamReaderStreamReader ReadToEnd
Summary. The File.ReadAllText function reads the entire text contents into a String. For simplicity, this is the best method to use. More advanced methods can be used to read files in line-by-line, which is more efficient with large files.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.