Contact US

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Checking for existing files

Checking for existing files

Checking for existing files

I am new to VB and was wondering how to go about checking to see if the file name the program has created already exists. I could use the commondialog1.showsave , Flag 2, but I don't want to see the dialog box. I just want the program to ask me if I want to overwrite the existing file.

Any clues?



RE: Checking for existing files

You can use the Dir() function.

While I welcome e-mail messages, please post all thread activity in these forums for the benefit of all members.

RE: Checking for existing files

Public Function FileExists%(filename$, showErr As Boolean)
' Description
'     Checks 'filename$' to find whether the filename given
'     exists.
' Parameters
'     Name              Type     Value
'     -------------------------------------------------------------
'     filename$         String   The filename to be checked
' Returns
'     True if the file exists
'     False if the file does not exist
Dim f%
   ' Trap any errors that may occur
   On Error Resume Next
   ' Get a free file handle to avoid using a file handle already in use
   f% = FreeFile
   ' Open the file for reading
   Open filename$ For Input As #f%
   ' Close it
   Close #f%
   ' If there was an error, Err will be <> 0. In that case, we return False
   FileExists% = Not (Err <> 0) Or Err = 70
   If Not FileExists% And showErr Then MsgBox (Err.Description)
   Err = 0
End Function

RE: Checking for existing files

This is the Object Oriented way of doing what you request, and is now the preferred method using the VB file object:

If the function returns True then the file was created, if it returns false then the file already existed or an error occurred.

You must put a reference in to Microsoft Scripting Runtime, do this by selecting Project on the menu, click on References, find then tick Microsoft Scripting Runtime.

Private Function CreateFile(sFileName As String) As Boolean
On Error GoTo err_cmdCreateFile_Click
Dim oFileSystemObject As FileSystemObject
Dim oFolder As Folder
Dim oStream As TextStream
'You use the TextStream object to read and write
'to the file, experiment with it.

If sFileName = "" Then
    sFileName = InputBox ("Enter a file name.", _
                "Missing File Name")
End If
Set oFileSystemObject = CreateObject("Scripting.FileSystemObject")

'Check that the destination folder exists
'Replace Temp with any filepath name
If oFileSystemObject.FolderExists("C:\temp") Then
    Set oFolder = oFileSystemObject.GetFolder("C:\Temp")
    Set oFolder = oFileSystemObject.CreateFolder("C:\Temp")
End If

'Check does file exist
If oFileSystemObject.FileExists("C:\Temp\" & sFileName) Then
    MsgBox "File already exists.", vbOKOnly
    CreateFile = False

    Set oStream = oFileSystemObject.CreateTextFile _  
                  ("C:\Temp\" & sFileName, True, True)
    CreateFile = True

End If

Set oStream = oFileSystemObject.CreateTextFile("C:\Temp\" _
            & sFileName, True, True)

    Set oFileSystemObject = Nothing

    Exit Sub

    MsgBox "Error number " & Err.Number _
         & Err.Description

    CreateFile = False
    GoTo exit_CreateFile
End Sub

Any problems let me know!


RE: Checking for existing files

Thanks for all your pervious help, I now have a revised idea of what exactly what I need. It is as follows:

I have a program that creates a file name based on give parameters. The file name format is as follows:

Drive:\Main Directory\***\***1234?.ext

*** = 3 letter code

? = a single letter

Now what I need my code to do is search the *** sub-directory for the new file name minus the last letter ‘?’
If it finds a match(s) I want it to list it(them) in a window and ask the user if they want to delete the old file(s).

I also need the code to let the user know if the exact file name already exists and to ask if they want to overwrite or cancel.

Any help will be great.



RE: Checking for existing files

Use the previous code I gave you but manipulate the filename to achieve the result you require, it's fairly simple to do and should need no further explanation.

RE: Checking for existing files

Use Dir(), if file dosen't exist, it will return ""

dongxiao PEng

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Eng-Tips forums is a member-only feature.

Click Here to join Eng-Tips and talk with other members! Already a Member? Login


Low-Volume Rapid Injection Molding With 3D Printed Molds
Learn methods and guidelines for using stereolithography (SLA) 3D printed molds in the injection molding process to lower costs and lead time. Discover how this hybrid manufacturing process enables on-demand mold fabrication to quickly produce small batches of thermoplastic parts. Download Now
Design for Additive Manufacturing (DfAM)
Examine how the principles of DfAM upend many of the long-standing rules around manufacturability - allowing engineers and designers to place a part’s function at the center of their design considerations. Download Now
Taking Control of Engineering Documents
This ebook covers tips for creating and managing workflows, security best practices and protection of intellectual property, Cloud vs. on-premise software solutions, CAD file management, compliance, and more. Download Now

Close Box

Join Eng-Tips® Today!

Join your peers on the Internet's largest technical engineering professional community.
It's easy to join and it's free.

Here's Why Members Love Eng-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close