VB.Net program to copy the content of one file to another file by overwriting the file

Here, we are going to learn how to copy the content of one file to another file by overwriting the file in VB.Net?
Submitted by Nidhi, on January 10, 2021 [Last updated : March 08, 2023]

Copying the content of one file to another file by overwriting the file in VB.Net

Here, we will use the Copy() method of File class with "true" value to overwrite the content of the file.

Program/Source Code:

The source code to copy the content of one file to another file by overwriting the file is given below. The given program is compiled and executed successfully.

VB.Net code to copy the content of one file to another file by overwriting the file

'VB.Net program to copy the content of one file to another file 
'by overwriting the file, if the file has the same name.

Imports System.IO

Module Module1
    Sub Main()
        Try
            Dim data As String

            Console.WriteLine("Content Before copy:" & vbCrLf)
            data = File.ReadAllText("source/abc.txt")
            Console.WriteLine("Content of source/abc.txt :" & vbCrLf & data)

            data = File.ReadAllText("dest/abc.txt")
            Console.WriteLine("Content of dest/abc.txt :" & vbCrLf & data & vbCrLf & vbCrLf & vbCrLf)

            File.Copy("source/abc.txt", "dest/abc.txt", True)

            Console.WriteLine("Content After copy:" & vbCrLf)
            data = File.ReadAllText("source/abc.txt")
            Console.WriteLine("Content of source/abc.txt :" & vbCrLf & data)

            data = File.ReadAllText("dest/abc.txt")
            Console.WriteLine("Content of dest/abc.txt :" & vbCrLf & data)

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

Output

Content Before copy:

Content of source/abc.txt :
Hello, How are you?
Content of dest/abc.txt :
Think big, Think beyond.


Content After copy:

Content of source/abc.txt :
Hello, How are you?
Content of dest/abc.txt :
Hello, How are you?

Explanation

In the above program, we created the module Module1 that contains the Main() function. The Main() function is the entry point for the program.

Here, we copied the content of 'source/abc.txt' to 'dest/abc.txt' and In the above Copy method there is a third Boolean parameter is used to allow/deny overwriting content in case of the same file name.

VB.Net File Handling Programs »






Comments and Discussions!

Load comments ↻






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