Home > VB.NET > Check If File Exists with VB.NET

Check If File Exists with VB.NET

I was creating an application in Visual Basic the other day and I couldn’t remember how to check to see if a file exists, so I thought I would do a quick example to see if a file exitsts. If the file exists, the program will continue on, however, if the file doesn’t exist you will get a message box saying that the file does not exist, and the application will exit.

1
2
3
4
If System.IO.File.Exists("C:\MyDocs\MyFile.txt") = False Then
   MsgBox("Field does not exist!", MsgBoxStyle.Critical, "File Not Found")
   Application.Exit()
End If

If you have an Imports System.IO call in your program, then you can shorten the method call by deleting the System.IO class name, which would give you.

1
2
3
4
If File.Exists("C:\MyDocs\MyFile.txt") = False Then
   MsgBox("Field does not exist!", MsgBoxStyle.Critical, "File Not Found")
   Application.Exit()
End If

This method call is supported in .NET Framework version 3.5, 3.0, 2.0, 1.1, and 1.0.

Categories: VB.NET Tags: , ,
  1. Arnab
    September 5th, 2009 at 03:49 | #1

    Thanks for the code. But a problem with this code is it can not find whether a file exists in the network. 🙁

  2. September 5th, 2009 at 22:42 | #2

    Arnab, you are correct, this code only works on a local file, I’ll try and update it when I get a chance for network (or UNC) files.

  3. September 7th, 2009 at 12:57 | #3

    Arnab, correction to my correction 🙂 I just tested this out and it turns out that you can in fact use this class to access network files.

  1. No trackbacks yet.
You must be logged in to post a comment.