How to Copy , Delete File in VB.NET

The File class in the System.IO namespace provides a comprehensive set of operations for working with files. Developers can utilize this class to perform tasks such as copying, moving, renaming, creating, opening, deleting, and appending to files. These operations enable efficient file management within VB.NET applications.

File.Copy("c:\\temp.txt", "c:\\copytemp.txt", True) File.Delete("c:\\copytemp.txt")


IOException serves as the base class for exceptions that may occur while accessing information using streams, files, and directories. It captures a range of potential exceptions related to input/output operations, including issues with reading or writing data, accessing files, or manipulating directories. By handling or catching IOException, developers can manage errors and exceptions related to file operations.

Try 'code here Catch ex As System.IO.FileNotFoundException 'exception here End Try

In specific cases where an attempt is made to access a file that does not exist on disk, the FileNotFoundException class is thrown. This exception is raised when the application tries to access a file that cannot be found at the specified path. FileNotFoundException provides developers with an indication that the requested file is missing, allowing them to handle this situation accordingly and take appropriate action.

The following program shows how to use File Class for copying and deleting a text file and also its shows how to handle System.IO.FileNotFoundException Class.

Full Source VB.NET
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try File.Copy("c:\\temp.txt", "c:\\copytemp.txt", True) File.Delete("c:\\copytemp.txt") Catch ex As System.IO.FileNotFoundException MsgBox(ex.ToString()) End Try End Sub End Class


By using the File class and being aware of exception classes like IOException and FileNotFoundException, developers can effectively manage file-related operations in their VB.NET applications. These classes and exception mechanisms provide a robust framework for working with files, ensuring proper error handling and allowing for recovery from potential issues.