2 Replies - 3727 Views - Last Post: 06 March 2011 - 12:47 PM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Check if a file exists in VB6

Posted 02 March 2008 - 10:35 AM

Description: Here we will use the GetAttr Function to retrieve the attributes of the file provided. If the file doesn't exist it will generate an error, which we catch using On Error GoToThis is a snippet for checking if a file exists in VB6
Function DoesExist(file As String) As Boolean
    On Error GoTo Error
    'get the file attributes, and make sure what
    'is being passed isnt a directory
    DoesExist = (GetAttr(file) And vbDirectory) = 0
Error:
    'Return False if an error occurs
    DoesExist = False
End Function


Is This A Good Question/Topic? 0
  • +

Replies To: Check if a file exists in VB6

#2 apolydorou   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 04-January 10

Re: Check if a file exists in VB6

Posted 08 August 2010 - 10:07 PM

please note : an 'exit sub' is required before Error: Otherwise it will just drop in to the error every time thanks
Was This Post Helpful? 0
  • +
  • -

#3 fadetonoir   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 06-March 11

Re: Check if a file exists in VB6

Posted 06 March 2011 - 12:47 PM

apolydorou is correct. This code always returns false because, even if it returns true at first, it's then set to false because it always runs the line under 'Error:'. However, you need to add 'Exit Function', not 'Exit Sub', obviously, because it's a function. The correct code should be: Function DoesExist(FilePath As String) As Boolean On Error GoTo Error 'Get the file attributes, and make sure what is being passed isnt a directory DoesExist = (GetAttr(FilePath) And vbDirectory) = 0 Exit Function Error: 'Return False if an error occurs DoesExist = False End Function Or, you can just omit the line after Error. So this also works: Function DoesExist(FilePath As String) As Boolean On Error GoTo Error 'Get the file attributes, and make sure what is being passed isnt a directory DoesExist = (GetAttr(FilePath) And vbDirectory) = 0 Error: 'Return False if an error occurs DoesExist = False End Function
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1