VB.Net program to append text into an already existing file

Here, we are going to learn how to append text into an already existing file in VB.Net?
Submitted by Nidhi, on January 08, 2021 [Last updated : March 08, 2023]

Appending text into a file in VB.Net

Here, we will read data from the text file and then read data from the user and append to the file using AppendAllText() method of File class.

Program/Source Code:

The source code to append text into the already existing file is given below. The given program is compiled and executed successfully.

VB.Net code to append text into an already existing file

'VB.Net program to append text into an already existing file.

Imports System.IO

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

        Try
            str = File.ReadAllText("sample.txt")

            Console.WriteLine("Content of file before append text: ")
            Console.WriteLine(str)

            Console.WriteLine("Enter text to append into file:")
            str = Console.ReadLine()

            File.AppendAllText("sample.txt", str)

            Console.WriteLine("Content after append:")
            str = File.ReadAllText("sample.txt")
            Console.WriteLine(str)


        Catch ex As FileNotFoundException
            Console.WriteLine("File does not exist")
        End Try
    End Sub
End Module

Output

Content of file before append text:
Hello, how are you.
Enter text to append into file:
I am fine.
Content after append:
Hello, how are you.I am fine.
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 then read data from the user and append data to the file using AppendAllText() method of File class. If the specified file does not exist in the computer system then a file not found exception gets generated and prints the appropriate message on the console screen.

VB.Net File Handling Programs »





Comments and Discussions!

Load comments ↻





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