Visual Basic

Visual Basic Delete File If Exists

To delete a file if it exists in Visual Basic .NET, call System.IO.File.Delete with the file's path. A missing file does not cause this method to throw, so a separate existence check is optional. Use File.Exists when you need conditional behaviour, and handle deletion errors.

Which licences fit your PC setup?

Prices are an AUD snapshot, not a live quote. Confirm variant and total on the listing.

Delete a single file in VB.NET

The examples below use VB.NET and the System.IO namespace. They are suitable for tasks such as removing a temporary export or cleaning up an application's working files. For other language fundamentals, browse our Visual Basic guides.

Start with a disposable text file in a folder you control. To adapt the example:

  1. Add the statement Imports System.IO at the top of your source file, before any class or module declarations.
  2. Inside a procedure, declare a string containing the full path of the file you intend to remove.
  3. Call File.Delete with that variable, handling the errors your application can encounter.

The core statements inside the procedure are:

Dim filePath As String = "C:\Temp\sample.txt"

File.Delete(filePath)

Dim declares the variable, As String specifies its type, and the quoted text supplies its value. If this syntax is unfamiliar, read what Dim means in Visual Basic before adapting the example.

Use an explicit path while learning so you can see exactly which file is targeted. Relative paths depend on the application's current working directory. Microsoft documents that a missing file is ignored, but an invalid path or other filesystem problem can still cause an exception. See the File.Delete reference.

Use File.Exists for conditional behaviour

An existence check is useful when the application needs to take a different action depending on whether it finds a file. For example, you might show a message before attempting deletion or skip other processing when no file is available.

With System.IO imported, the familiar conditional pattern is:

Dim filePath As String = "C:\Temp\sample.txt"

If File.Exists(filePath) Then

File.Delete(filePath)

End If

File.Exists returns a Boolean. However, False does not prove that the file is absent: the method also returns False for some errors, including insufficient access and invalid paths. It is not a path-validation tool.

The check and the deletion are separate operations. Another process can change the file between them, so a successful check does not guarantee a successful delete. Keep error handling around the operation itself. These limitations are explained in Microsoft's File.Exists documentation.

Handle deletion failures explicitly

A console application can report common failures with a Try...Catch block. Put the following statements inside a procedure, with System.IO imported at file level:

Dim filePath As String = "C:\Temp\sample.txt"

Try

File.Delete(filePath)

Catch ex As UnauthorizedAccessException

Console.WriteLine("Deletion was refused: " & ex.Message)

Catch ex As IOException

Console.WriteLine("A filesystem error prevented deletion: " & ex.Message)

End Try

This is an example of reporting failures, not an exhaustive handler for every possible input. In a desktop application, replace console output with an appropriate message or logging mechanism.

  • Access failures: check the application's permissions and whether the file is read-only.
  • Files in use: close streams opened by your application before deleting. A Using block helps dispose of a stream when its work is finished.
  • Path problems: check the folder, drive and supplied filename rather than retrying the same operation indefinitely.

Avoid an empty Catch block: it hides failures and can leave later code assuming cleanup succeeded. Record the affected path and the error, and decide whether that failure should stop the task or allow it to continue.

Choose permanent deletion or the Recycle Bin

File.Delete bypasses the Recycle Bin. You do not need to change file attributes to enable this behaviour, and there is no FileAttributes.RecycleBit setting. Clearing attributes is not a substitute for choosing the correct deletion method.

For an interactive Windows application that should send a file to the Recycle Bin, use the appropriate My.Computer.FileSystem.DeleteFile overload:

My.Computer.FileSystem.DeleteFile(filePath, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)

This statement assumes filePath has already been declared. Unlike File.Delete, this API can throw FileNotFoundException for a missing file. If disappearance is an acceptable outcome, handle that exception specifically; an existence check alone cannot prevent it.

The Recycle Bin and user-interface options are intended for interactive applications and are not supported in contexts such as Windows services. Check the DeleteFile overload documentation before selecting this approach.

Delete multiple files within a defined scope

For a known set of files, loop through their paths and apply the same deletion and error-handling logic to each. A straightforward For Each loop makes it easier to report which file failed than a compact LINQ expression.

To select files from one folder, Directory.GetFiles accepts a search pattern. For example, Directory.GetFiles(directoryPath, "*.tmp") returns matching paths from that directory without searching subfolders. The available search options are described in the Directory.GetFiles reference.

  1. Select an application-owned cleanup folder and a narrow filename pattern.
  2. List the matching paths for review before enabling deletion.
  3. Loop through the approved paths and handle failures for each file if cleanup should continue.
  4. Handle folder-access or enumeration failures separately from individual deletion failures.

If you are maintaining an older project, questions about its longer-term direction are covered in our discussion of whether Visual Basic .NET is dead.

Next, run the single-file example against a disposable file, then run it again after that file has gone. Confirm the missing-file behaviour before connecting the routine to your application's real cleanup task.

Other editions for separate workloads

Other editions for separate workloads; prices in AUD, confirm the total on the listing.

How to check this worked

  1. Open Settings, System, Activation and confirm the edition shown.
  2. Enter the key and run activation; expect a green tick within a minute.
  3. Reboot and re-check activation survives the restart.

FAQ

What else should you know before buying?

What do I need before starting?
Read the requirements and confirm the edition first; the steps assume the machine is compatible.
How do I know the licence is genuine?
Activate on Microsoft's servers and check Settings, System, Activation. A working activation is the test.
Is this a subscription?
Keys sold here are one-time lifetime licences. Microsoft 365 plans are billed by Microsoft instead.
What if the key fails?
Email hi@ms.codes with the order number and a screenshot. Replacement or refund applies within 30 days.

Check who prepared and reviewed this guide

Written by
MS.Codes editorial
Reviewed by
Support team

Last verified: (source review; see test status above).

Recent Post