×

VB.Net Programs

VB.Net program to replace the content of one file with another file and create a backup file

By Nidhi Last Updated : November 16, 2024

Replacing the content of one file with another file in VB.Net

Here, we will use the Replace() method of the File class to replace the content of one file with another and also create the backup file.

Program/Source Code:

The source code to replace the content of one file with another file and create a backup file is given below. The given program is compiled and executed successfully.

VB.Net code to replace the content of one file with another file and create a backup file

'VB.Net program to replace the content of one file 
'with another file and create the backup file.

Imports System.IO

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

        Try
            str = File.ReadAllText("sample.txt")
            Console.WriteLine("Content of sample.txt file: ")
            Console.WriteLine(str)

            str = File.ReadAllText("demo.txt")
            Console.WriteLine("Content of demo.txt file: ")
            Console.WriteLine(str)

            File.Replace("sample.txt", "demo.txt", "backup.txt")

            Console.WriteLine(vbCrLf & vbCrLf & "Content After Replace:" & vbCrLf)
            Console.WriteLine("Content of File(demo.txt):")
            str = File.ReadAllText("demo.txt")
            Console.WriteLine(str)

            Console.WriteLine("Content of File(backup.txt):")
            str = File.ReadAllText("backup.txt")
            Console.WriteLine(str)

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

Output

Content of sample.txt file:
Hello how are you.
Content of demo.txt file:
it is demo file.


Content After Replace:

Content of File(demo.txt):
Hello how are you.
Content of File(backup.txt):
it is demo file.
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" and "demo.txt" file and then replace the content of the "sample.txt" file with "demo.txt" file and create a backup file "backup.txt" using Replace() method of File class.

If any 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.