February 1, 2010

How to Check if File Exists (VB)

How to check to see if a file exists before allowing an upload to your server.
In your Upload code-behind add the following lines to your btn_click sub:
...
If System.IO.File.Exists(path & Upload1.Filename) THEN
code on what to do if it exists
End If
...
Here is an example of my code with some error handling and reporting lines. You will need to change the generic objects to your id names:

Protected Sub btn_Upload1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Upload1.Click
If Upload1.HasFile Then
Dim ext As String
Dim savefile As String
ext = System.IO.Path.GetExtension(Upload1.FileName)

If (ext = ".jpg" Or ext = ".gif" Or ext = ".jpeg" Or ext = ".png" Or ext = ".bmp") Then
savefile = "(Filepath & Upload1.FileName
FileLabel2.Visible = False
Try
If System.IO.File.Exists( Filepath & Upload1.FileName) Then
FileLabel1.Visible = True
FileLabel1.Text = "File already exists. Upload cancelled."
Else
Upload1.SaveAs(Server.MapPath(savefile))
FileLabel1.Visible = True
FileLabel1.Text = "File Name: " & Upload1.PostedFile.FileName & "
" & "File size: " & Upload1.PostedFile.ContentLength & " kb
" & "Type: " & Upload1.PostedFile.ContentType & "
<img src ='" & savefile & "'>"
End If
Catch ex As Exception
FileLabel1.Text = "Error: " & ex.Message.ToString()
End Try
Else
FileLabel2.Visible = True
FileLabel2.Text = " Please specify only Image files to upload."
End If
Else
FileLabel2.Visible = True
FileLabel2.Text = "Your Upload did not upload."
End If
End Sub

Hope this is helpful.