×

VB.Net Programs

VB.Net program to read data from a text file

By Nidhi Last Updated : November 16, 2024

Reading data from a text file in VB.Net

Here, we will read data from a text file using ReadAllText() method of the File class. If the specified file does not exist in the system then a FileNotFoundException gets generated.

Program/Source Code:

The source code to read data from a text file is given below. The given program is compiled and executed successfully.

VB.Net code to read data from a text file

'VB.Net program to read data from a text file.

Imports System.IO

Module Module1
    Sub Main()
        Dim str As String = Nothing

        Try
            str = File.ReadAllText("sample.txt")
            Console.WriteLine("Content of file: {0}", str)
        Catch ex As FileNotFoundException
            Console.WriteLine("File does not exist")
        End Try
    End Sub
End Module

Output

Content of file: Hello, how are you.
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains the Main() function. The Main() function is the entry point for the program. And, we created a local variable str of string type. After that read data from the "sample.txt" text file and print data on the console screen. If a specified file does not exist in the computer system then a file not found exception gets generated and prints an appropriate message on the console screen.

VB.Net File Handling Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.