Results 1 to 40 of 40

Thread: how to delete file using visual basic 6.0

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2006
    Posts
    17

    how to delete file using visual basic 6.0

    hello everyone,

    i want to delete a file which is in a folder. i know the name and path of that file. how can i delete using code of visual basic 6.0

  2. #2
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: how to delete file using visual basic 6.0

    VB Code:
    1. Kill "C:\test\text.txt"

  3. #3
    Fanatic Member vivek_master146's Avatar
    Join Date
    Apr 2006
    Location
    Delhi,India
    Posts
    787

    Thumbs up Re: how to delete file using visual basic 6.0

    This is for deleting a file if it is not read-only. If u want to delete read-only files alo use:

    VB Code:
    1. Private Sub filedelete(filename As String)
    2. Dim filesystemobject As Object
    3. Set filesystemobject = CreateObject("Scripting.filesystemobject")
    4. filesystemobject.deletefile filename, True
    5. End Sub
    6.  
    7.  
    8.  
    9.  
    10. Private Sub Command1_Click()
    11. filedelete (filename)
    12. End Sub
    Dont rely only on your luck. Work hard until You get success.
    vb Code:
    1. Private sub Time_ispassing
    2. While Me.Notgetsuccess
    3. trygain=tryagain+1
    4. Me.workhard
    5. wend
    6. end sub

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Apr 2006
    Posts
    17

    thanks

    thank you bushmobile for your positive response. i got that.

  5. #5
    Hyperactive Member Jenova's Avatar
    Join Date
    Feb 2006
    Location
    Googleplex
    Posts
    413

    Re: how to delete file using visual basic 6.0

    There is an API call for this.

    VB Code:
    1. Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" _
    2.                         (ByVal lpFileName As String) _
    3.                          As Long
    4.  
    5. Private Sub Command1_Click()
    6.     Dim File As String
    7.     ' Change Directory where neccesary
    8.     File = "C:\WINDOWS\Sample.txt"
    9.     DeleteFile File
    10. End Sub

    Hope this helps you

    Jenova

  6. #6
    Member Croftage's Avatar
    Join Date
    Feb 2006
    Location
    Lincoln
    Posts
    47

    Re: how to delete file using visual basic 6.0

    Yer I agree with the

    Kill "c:\log.txt"

    But don't forget it doesn't send it to the recycle bin, it just deletes it forever
    Today a young man on acid realized that we are all energy condensed to slow vibrations, we are all one consciousness experiencing itself subjectively. There is no such thing as death, life is only an illusion and we are the imagination of ourselves

  7. #7
    Fanatic Member vivek_master146's Avatar
    Join Date
    Apr 2006
    Location
    Delhi,India
    Posts
    787

    Re: how to delete file using visual basic 6.0

    I m in hurry. anshu if u want then i can send u the code to delete a file and then send it to recycle bin.
    Dont rely only on your luck. Work hard until You get success.
    vb Code:
    1. Private sub Time_ispassing
    2. While Me.Notgetsuccess
    3. trygain=tryagain+1
    4. Me.workhard
    5. wend
    6. end sub

  8. #8
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: how to delete file using visual basic 6.0

    Use SHFileOperation to send a file to the recycle bin.
    VB Code:
    1. Private Declare Function SHFileOperation _
    2.  Lib "shell32.dll" Alias "SHFileOperationA" ( _
    3.     lpFileOp As SHFILEOPSTRUCT _
    4. ) As Long
    5.  
    6. Private Const FO_DELETE = &H3
    7. Private Const FOF_ALLOWUNDO = &H40
    8.  
    9. Private Type SHFILEOPSTRUCT
    10.     hwnd As Long
    11.     wFunc As Long
    12.     pFrom As String
    13.     pTo As String
    14.     fFlags As Integer
    15.     fAborted As Boolean
    16.     hNameMaps As Long
    17.     sProgress As String
    18. End Type
    19.  
    20. Public Sub DeleteFile(ByVal sFileName As String)
    21.     Dim fo As SHFILEOPSTRUCT
    22.     With fo
    23.         .pFrom = sFileName & vbNullChar
    24.         .wFunc = FO_DELETE
    25.         .fFlags = FOF_ALLOWUNDO
    26.     End With
    27.     Call SHFileOperation(fo)
    28. End Sub
    Now simply call DeleteFile with the path and name of the file to send to the recycle bin.

  9. #9
    Frenzied Member wengang's Avatar
    Join Date
    Mar 2000
    Location
    Beijing, China
    Posts
    1,604

    Re: how to delete file using visual basic 6.0

    Joacim (or anybody), this is a good method, but how do I know if the user clicked yes or no on the "Are you sure you want to....." dialog box?
    I know I could just check to see if the file is still there, but is there a way to get feedback from this process as to which button the user clicked?
    Wen Gang, Programmer
    VB6, QB, HTML, ASP, VBScript, Visual C++, Java

  10. #10
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: how to delete file using visual basic 6.0

    For reals? You don't know how a simple MsgBox works? And you dragged up a FIFTEEN year old thread in the process?

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  11. #11
    Member
    Join Date
    Jul 2020
    Posts
    38

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by wengang View Post
    Joacim (or anybody), this is a good method, but how do I know if the user clicked yes or no on the "Are you sure you want to....." dialog box?
    I know I could just check to see if the file is still there, but is there a way to get feedback from this process as to which button the user clicked?
    Something like this?

    Code:
    Public Sub Delete_File(ByVal vPathOfFile As String)
        Dim vStartTime As Date: vStartTime = Now
        
        If Dir(vPathOfFile, vbArchive Or vbHidden) <> "" Then
            If MsgBox("Do you want to delete the file?", vbYesNo, "Warning") = vbYes Then   ' < Here is the section you needed to know
                If Dir(vPathOfFile, vbArchive Or vbHidden) <> "" Then
                    SetAttr vPathOfFile, vbArchive
                    Kill vPathOfFile
                End If
                
                Do
                    If DateDiff("s", vStartTime, Now) >= 5 Then Exit Do
                Loop Until Dir(vPathOfFile, vbArchive Or vbHidden) = ""
                
                If Dir(vPathOfFile, vbArchive Or vbHidden) = "" Then MsgBox "File deleted successfully" Else MsgBox "Error deleting file"
            End If
        End If
    End Sub
    Example:
    Delete_File "C:\My folder\My file.txt"

    Have a nice day

  12. #12
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,910

    Re: how to delete file using visual basic 6.0

    I think he's asking how we'd know if the Windows delete confirmation is on (or off). Personally, I don't know how to tell, but I'm certain is some buried registry setting somewhere.

    Also, VB6's "Kill" statement ignores that setting, so it's somewhat moot (unless we're using File Explorer to do our deletes for us).
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  13. #13
    Hyperactive Member gilman's Avatar
    Join Date
    Jan 2017
    Location
    Bilbao
    Posts
    273

    Re: how to delete file using visual basic 6.0

    see the returned value in fAborted
    https://docs.microsoft.com/en-us/win...Type%3A%20BOOL
    Last edited by gilman; Jun 4th, 2022 at 02:32 AM.

  14. #14
    Member
    Join Date
    Jul 2020
    Posts
    38

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by Elroy View Post
    I think he's asking how we'd know if the Windows delete confirmation is on (or off). Personally, I don't know how to tell, but I'm certain is some buried registry setting somewhere.

    Also, VB6's "Kill" statement ignores that setting, so it's somewhat moot (unless we're using File Explorer to do our deletes for us).
    Quote Originally Posted by gilman View Post
    Thanks!
    So...

    VB Code:
    1. Private Declare Function SHFileOperation _
    2.      Lib "shell32.dll" Alias "SHFileOperationA" ( _
    3.         lpFileOp As SHFILEOPSTRUCT _
    4.     ) As Long
    5.      
    6. Private Const FO_DELETE = &H3
    7. Private Const FOF_ALLOWUNDO = &H40
    8.      
    9. Private Type SHFILEOPSTRUCT
    10.     hwnd As Long
    11.     wFunc As Long
    12.     pFrom As String
    13.     pTo As String
    14.     fFlags As Integer
    15.     fAborted As Boolean
    16.     hNameMaps As Long
    17.     sProgress As String
    18. End Type
    19.      
    20. Public Function DeleteFile(ByVal sFileName As String, Optional vRecycleBin As Boolean) As Boolean
    21.     Dim fo As SHFILEOPSTRUCT
    22.    
    23.     With fo
    24.         .pFrom = sFileName & vbNullChar
    25.         .wFunc = FO_DELETE
    26.         If vRecycleBin Then .fFlags = FOF_ALLOWUNDO    ' Send to RecycleBin
    27.     End With
    28.    
    29.     Call SHFileOperation(fo)
    30.     DeleteFile = Abs(fo.fAborted) - 1
    31. End Function

    Examples:

    Code:
    If DeleteFile("C:\My folder\My file.txt") Then
        MsgBox "File deleted"
    Else
        MsgBox "Aborted"
    End If
    Or...

    Code:
    If DeleteFile("C:\My folder\My file.txt", True) Then
        MsgBox "File sent to RecycleBin"
    Else
        MsgBox "Aborted"
    End If
    See ya

  15. #15
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Sorry to resurrect an old thread but I cannot get the kill command to work. I have read and read and read the various threads about this problem but none of the solutions seem to work for me.

    I am trying to delete a text file from a non protected directory on a machine where I have admin rights. Specifically:

    Code:
    Dim TempString As String
    
    TempString = "C:\Test Directory\Test.txt"
    
    Kill TempString
    The file remains and there is no indication it didn't work (no errors thrown) other than the file remains

  16. #16
    PowerPoster
    Join Date
    Jul 2010
    Location
    NYC
    Posts
    7,654

    Re: how to delete file using visual basic 6.0

    Sometimes it takes a few minutes for a deleted file to fully disappear.

    Or is it possible you've suppressed errors (e.g. On Error Resume Next) and are trying to delete a read only file? (in which case you need only remove the Read Only attribute first, SetAttr TempString, vbNormal)

  17. #17
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by KenHorse View Post
    Sorry to resurrect an old thread but I cannot get the kill command to work. I have read and read and read the various threads about this problem but none of the solutions seem to work for me.

    I am trying to delete a text file from a non protected directory on a machine where I have admin rights. Specifically:

    Code:
    Dim TempString As String
    
    TempString = "C:\Test Directory\Test.txt"
    
    Kill TempString
    The file remains and there is no indication it didn't work (no errors thrown) other than the file remains
    Shot in the dark, since there is a space in the path:

    Code:
    TempString = Chr(34) & "C:\Test Directory\Test.txt" & Chr(34)

  18. #18
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    File is not RO.

    Thanks for the suggestion OptionBase1 but that didn't work either.

    I've even tried

    Code:
    Public Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String, ByVal bFailIfExists As Long) As Long
    DeleteAFile TempString, 0

    With the same (ineffective) results
    Last edited by KenHorse; Jan 1st, 2024 at 03:30 PM.

  19. #19
    Fanatic Member
    Join Date
    Mar 2023
    Posts
    976

    Re: how to delete file using visual basic 6.0

    This shell32 API is really nasty...it DOES overrun/ignores ALL the dialoges the shell is so famous for so this does it really "infamous"

    Code:
    Public Declare Function Win32DeleteFile Lib "shell32.dll" (ByVal pszPath As Long) As Long
    It deletes the folder and ALL the subfolders in a blink (without sending them to the recycle bin) and updates the Explorer.exe before you even had said "hmm"

    So this API is TERMINAL for a Folder!!

  20. #20
    PowerPoster VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    2,622

    Wink Re: how to delete file using visual basic 6.0

    Quote Originally Posted by Urbin View Post
    [code]
    Public Function DeleteFile(ByVal sFileName As String, Optional vRecycleBin As Boolean) As Boolean
    Dim fo As SHFILEOPSTRUCT

    With fo
    .pFrom = sFileName & vbNullChar
    .wFunc = FO_DELETE
    If vRecycleBin Then .fFlags = FOF_ALLOWUNDO ' Send to RecycleBin
    End With

    Call SHFileOperation(fo)
    DeleteFile = Abs(fo.fAborted) - 1
    End Function

    Examples:

    Code:
    If DeleteFile("C:\My folder\My file.txt") Then
        MsgBox "File deleted"
    Else
        MsgBox "Aborted"
    End If
    Or...

    Code:
    If DeleteFile("C:\My folder\My file.txt", True) Then
        MsgBox "File sent to RecycleBin"
    Else
        MsgBox "Aborted"
    End If
    See ya
    "SHFileOperation" requires the file name string to be double null terminated otherwise bad things can happen! It's a dangerous API to use improperly. It has an advantage though, namely it allows wildcards (*) in the file name so it can delete multiple files at once:

    Code:
    Public Function FileDeleteWildcard(sPath As String) As Long
    Dim tFOS As SHFILEOPSTRUCT, sBuffer As String
    Const FOF_NO_UI As Long = FOF_SILENT Or FOF_NOCONFIRMATION Or FOF_NOCONFIRMMKDIR Or &H400 ' FOF_NOERRORUI
        sBuffer = String$(cMaxPath, vbNullChar): Mid$(sBuffer, 1) = sPath
        With tFOS: .pFrom = StrPtr(sBuffer): .wFunc = FO_DELETE: .fFlags = FOF_NO_UI: End With
        FileDeleteWildcard = SHFileOperationW(VarPtr(tFOS))
    End Function
    If you only want to delete a single file then "DeleteFileW" does the job:

    Code:
    Private Declare Function DeleteFileW Lib "kernel32" (ByVal lpFileName As Long) As Long

  21. #21
    PowerPoster
    Join Date
    Jul 2010
    Location
    NYC
    Posts
    7,654

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by KenHorse View Post
    File is not RO.

    Thanks for the suggestion OptionBase1 but that didn't work either.

    I've even tried

    Code:
    Public Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String, ByVal bFailIfExists As Long) As Long
    DeleteAFile TempString, 0

    With the same (ineffective) results
    See if there's an error...

    Code:
    If DeleteFile(TempString, 0) Then
    Debug.Print "success"
    Else
    Debug.Print "Error: " & Err.LastDllError
    If it prints 'Success', then the problem is outside of VB.

  22. #22
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    It prints success (and if I modify the code to report error code) and a 0

    I don't see what might prevent it from working however as EVERYONE on this machine has complete access to this computer's file system.

    It is Win 11 if that makes any difference

  23. #23
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Are you able to manually delete the file yourself via Windows Explorer? If so, does the file re-appear somehow on it's own?

  24. #24
    Fanatic Member
    Join Date
    Mar 2023
    Posts
    976

    Re: how to delete file using visual basic 6.0

    Use this and you don't have to bother more of that file or folder or iif it prints success...
    Code:
    Public Declare Function Win32DeleteFile Lib "shell32.dll" (ByVal pszPath As Long) As Long

  25. #25
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Yup, no problem manually deleting it and it does not re-appear on its own, nope

  26. #26
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by nebeln View Post
    Use this and you don't have to bother more of that file or folder or iif it prints success...
    Code:
    Public Declare Function Win32DeleteFile Lib "shell32.dll" (ByVal pszPath As Long) As Long
    I was thinking just formatting the drive or better yet, re-partitioning it

  27. #27
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    I would start to question if you have some sort of antivirus/antimalware software installed that is doing some sort of activity monitoring and preventing an "unsigned" exe file from deleting files that don't appear related to the exe file. Complete shot in the dark, though.

  28. #28
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by OptionBase1 View Post
    I would start to question if you have some sort of antivirus/antimalware software installed that is doing some sort of activity monitoring and preventing an "unsigned" exe file from deleting files that don't appear related to the exe file. Complete shot in the dark, though.
    The same program copies the file before I try to delete it and the copy works just fine

  29. #29
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by KenHorse View Post
    The same program copies the file before I try to delete it and the copy works just fine
    Ok. That doesn't really matter much in regards to what I posted. Are you running any sort of AV/antimalware software? If so, can you disable it and see if the file deletion starts working?

  30. #30
    PowerPoster VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    2,622

    Talking Re: how to delete file using visual basic 6.0

    Quote Originally Posted by KenHorse View Post
    File is not RO.

    Thanks for the suggestion OptionBase1 but that didn't work either.

    I've even tried

    Code:
    Public Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String, ByVal bFailIfExists As Long) As Long
    DeleteAFile TempString, 0

    With the same (ineffective) results
    According to MSDN, the "DeleteFile" function only has one parameter (namely the file name). Your declaration is incorrect so probably that's why it doesn't work.

  31. #31
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by VanGoghGaming View Post
    According to MSDN, the "DeleteFile" function only has one parameter (namely the file name). Your declaration is incorrect so probably that's why it doesn't work.
    Ok, changed that and now it errors out with code 32

  32. #32
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by KenHorse View Post
    Ok, changed that and now it errors out with code 32
    File in use by another process I believe. So, what is happening with this file (either in your code or outside of your code) before you try to delete it?

  33. #33
    Fanatic Member
    Join Date
    Mar 2023
    Posts
    976

    Re: how to delete file using visual basic 6.0

    I do beleve Win32DeleteFile API ignores all this...try to delete Explorer.exe or shell32.dll with Win32DeleteFile API.

  34. #34
    Fanatic Member
    Join Date
    Mar 2023
    Posts
    976

    Re: how to delete file using visual basic 6.0

    Win32DeleteFile returns 1 on MsgBox Win32DeleteFile(StrPtr("C:\Windows\explorer.exe"))
    But it still remains in the Windows folder.

  35. #35
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by OptionBase1 View Post
    File in use by another process I believe. So, what is happening with this file (either in your code or outside of your code) before you try to delete it?
    I can see no other process using that file and have to think I wouldn't be able to delete it from Windows Explorer if it actually was in use, no? Very strange

  36. #36
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Is the only code in your program the code that tries to delete the file? Is there code in your program that interacts with that file that perhaps doesn't complete or close the file before you try to delete it?

    Good luck.

  37. #37
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    Quote Originally Posted by OptionBase1 View Post
    Is the only code in your program the code that tries to delete the file? Is there code in your program that interacts with that file that perhaps doesn't complete or close the file before you try to delete it?

    Good luck.
    Yea, I do a definite Close statement well before I try to delete it. This makes no sense to me. Anyway, I appreciate everyone's assist with this but I'm gonna call it a day for now. Happy New Year!

  38. #38
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,632

    Re: how to delete file using visual basic 6.0

    Rather than making us guess what your code is doing, at this point you should be posting all the code that touches that file.

  39. #39
    PowerPoster
    Join Date
    Jul 2010
    Location
    NYC
    Posts
    7,654

    Re: how to delete file using visual basic 6.0

    You can use a tool like ProcessHacker to find the process which has it open (for PH, under the Hacker menu, 'Find files or DLLs').

    If it's your own, or VB6 when running in the IDE, you haven't properly closed it. If it's another app, see why that has it open, and if you could automate closing it if need be.

    You *could* forcibly delete it with some advanced methods, but that's not a good idea.

    Another option is you could set it to be deleted on reboot;

    Code:
    Public Enum MoveFileExFlags
        MOVEFILE_REPLACE_EXISTING = &H00000001
        MOVEFILE_COPY_ALLOWED  = &H00000002
        MOVEFILE_DELAY_UNTIL_REBOOT  = &H00000004
        MOVEFILE_WRITE_THROUGH  = &H00000008
        MOVEFILE_CREATE_HARDLINK  = &H00000010
        MOVEFILE_FAIL_IF_NOT_TRACKABLE  = &H00000020
    End Enum
    
    #If VBA7 Then
    Public Declare PtrSafe Function MoveFileExW Lib "kernel32" (ByVal lpExistingFileName As LongPtr, ByVal lpNewFileName As LongPtr, ByVal dwFlags As MoveFileExFlags) As Long
    #Else
    Public Declare Function MoveFileExW Lib "kernel32" (ByVal lpExistingFileName As Long, ByVal lpNewFileName As Long, ByVal dwFlags As MoveFileExFlags) As Long
    #End If
    Then use MoveFileExW StrPtr(TempString), 0, MOVEFILE_DELAY_UNTIL_REBOOT

  40. #40
    Addicted Member
    Join Date
    Feb 2007
    Posts
    130

    Re: how to delete file using visual basic 6.0

    A final followup on this.

    Turns out that old issue of needing a 2nd set of eyes to see something that I kept missing, was needed (yes, I should have posted my code). I was not properly closing the file before I was trying to delete it. Sorry to taken y'all's time and again, thanks for the help

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width