how I can i delete a file if it exist with VBS

hello,

I have this code
Sub WriteDat(texte)
    On Error Resume Next
    Const ForAppending = 8
    Set fso = CreateObject("Scripting.FileSystemObject")
    set tf = fso.OpenTextFile("C:\TAS\file.dat", ForAppending, True)
    tf.writeline texte
    tf.Close

 On Error GOTO 0
End Sub

Open in new window


and i need to verify before writing the text if the file "file.dat " exist or not in my folder ,
if it exist i need to delete it then create and write on my file
i know that i need to add DeleteFile but i don't know how ..
someone can help me please ?
mell lian90Asked:
Who is Participating?
 
Bill PrewCommented:
Based on what you described I don't think you need to do as much as you think.  If you change the OpenTextFile to be ForWriting, then it will overwrite the file if it exists, or create it if it doesn't.  Sounds like you don't want Append mode...

Sub WriteDat(texte)
    On Error Resume Next
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8
    Set fso = CreateObject("Scripting.FileSystemObject")
    set tf = fso.OpenTextFile("C:\TAS\file.dat", ForWriting, True)
    tf.writeline texte
    tf.Close

    On Error GOTO 0
End Sub

Open in new window


»bp
1
 
Bill PrewCommented:
If you really do need to do a delete though, it would look like:

    If fso.FileExists("C:\TAS\file.dat") Then
        fso.DeleteFile("C:\TAS\file.dat")
    End If

Open in new window


»bp
0
 
mell lian90Author Commented:
hi @ Bill Prew ,

can you plese tel me how i can add the plow code
  If fso.FileExists("C:\TAS\file.dat") Then
        fso.DeleteFile("C:\TAS\file.dat")
    End If

Open in new window

in my original code .. because it didn't work for me
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Bill PrewCommented:
Sub WriteDat(texte)
    On Error Resume Next
    Const ForAppending = 8
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists("C:\TAS\file.dat") Then
        fso.DeleteFile("C:\TAS\file.dat")
    End If

    set tf = fso.OpenTextFile("C:\TAS\file.dat", ForAppending, True)
    tf.writeline texte
    tf.Close

 On Error GOTO 0
End Sub

Open in new window


»bp
0
 
mell lian90Author Commented:
thanks for your help Bill Prew ..
it's work for me but with the use of 2 functions , the first for ForAppending and the second ForWriting
thanks ..
0
 
mell lian90Author Commented:
i use this solution to resolve my issue
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.