How To Replace a File Using VB.NET

This article describes how to replace a file with other file in VB.NET.
  • 8241

Replace a File Using VB.NET

The Replace method replaces the contents of a specified file with the contents of another file. This method deletes the original file and creates a backup of the replaced file.
The following code snippet moves the contents of the original file into the replaced file and also creates a backup of the replaced file and deletes the original file.

Example:

Suppose we want to replace MaheshTXFITx.txt file with backup of MaheshTXFI.txt as MaheshTXFI.txt.bac. Before running below code file looks as:

Replace-file-in-nb.net.jpg


Module1.vb:


Imports System.Text

Imports System.IO

Module Module1

    Sub Main()

        Dim repFile As String = "C:\Temp\MaheshTXFI.txt"

        Dim backupFile As String = "C:\Temp\MaheshTXFI.txt.bac"

        Dim fileName As String = "C:\Temp\MaheshTXFITx.txt"

        Dim fi As New IO.FileInfo(fileName)

        Try

            fi.Replace(repFile, backupFile, False)

        Catch iox As IOException

            Console.WriteLine(iox.Message)

        End Try

    End Sub

End Module

Output:

Run above code and see file is replaced.
 

 File-replaced-in-vb.net.jpg


Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.