Solved

delete file

Posted on 2002-04-13
25
261 Views
Last Modified: 2010-05-02
hai experts:
 i have one question how to write in vb code to delete all the file with the certain extension like example *.mp3 from the "C:\" drive include subfolder. that mean the system will for all the mp3 file and delete it automatically. thank you very much and have a nice day
0
Comment
Question by:wong_k
  • 8
  • 5
  • 5
  • +6
25 Comments
 
LVL 2

Expert Comment

by:tppradeep18
ID: 6938614
you can use FileSystemObject which is available in Microsoft Windows Scripting library. REfer this library using projects->references.

Following is a sample code that I got from a site which calculates the count of numbre of folders within a folder. You can modify this code and do what you want.

use Kill statement to delete all .mp3 files within each folder

Public Function CountFolders(ByVal vsFolderName As String) As Long

    Dim oDirectory As clsDirectory
    Dim oFSO As FileSystemObject
    Dim oFolder As Folder
    Dim oSubFolder As Folder
    Dim lFolderCount As Long
   
    Set oFSO = New FileSystemObject
    Set oFolder = oFSO.GetFolder(vsFolderName)
    Set oDirectory = New clsDirectory
   
    lFolderCount = oFolder.SubFolders.Count
    For Each oSubFolder In oFolder.SubFolders
        lFolderCount = lFolderCount + oDirectory.CountFolders (oSubFolder.Path)
    Next
   
    Set oSubFolder = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing
   
    CountFolders = lFolderCount
   
End Function

0
 

Expert Comment

by:KrzysztofOblucki
ID: 6939188
from vb-faq.com, similar idea as the above

Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type


Private Declare Function APIFindFirstFile _
Lib "kernel32" _
Alias "FindFirstFileA" _
(ByVal lpFileName As String, _
lpFindFileData As WIN32_FIND_DATA) As Long

Private Declare Function APIFindNextFile _
Lib "kernel32" _
Alias "FindNextFileA" _
(ByVal hFindFile As Long, _
lpFindFileData As WIN32_FIND_DATA) As Long

Private Declare Function APIFindClose _
Lib "kernel32" _
Alias "FindClose" _
(ByVal hFindFile As Long) As Long

Private Declare Function GetShortPathName Lib "kernel32" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long
Private Declare Function GetFullPathName Lib "kernel32" Alias "GetFullPathNameA" (ByVal lpFileName As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
Private Declare Function FileTimeToLocalFileTime Lib "kernel32" (lpFileTime As FILETIME, lpLocalFileTime As FILETIME) As Long
Private Declare Function FileTimeToSystemTime Lib "kernel32" (lpFileTime As FILETIME, lpSystemTime As SYSTEMTIME) As Long



Public Function FindFile(ByVal pstrName As String) As Boolean

' FindFile: search for a file or directory
'
' Incoming parameters:
' pstrName (String): File to search for. This may contain ' any, all, or none of the following:
' a fully qualified path
' a specific file name
' wildcards (within file name only)
' If this item is null, "*.*" will be substituted.
' If no path is specified, the current directory will be ' searched.
'
' Returned parameters:
' Boolean: True if search is successful, false otherwise
'
' Global Variables Modified:
' hFind: Holds handle to opened Find for later use
' FileData: Receives file data returned from API
' sFullPath: Holds full path to located file, minus file name, for future use
' sShortPath: Holds short (8.3) path to located file, minus file name, for future use
'
' Local Variables:
' nPathLen (Long): Length of path name (used for creating buffer)
' pName (Long): Unused variable (pointer to short name - actual pointer, not offset)
' iPos (Integer): Offset of "\" when separating path and file name
' sName (String): Used to separate file name from path name
' bCont (Boolean): Used to detect when to end loop separating ' path and file name

Dim nPathLen As Long, pName As Long
Dim sName As String
Dim bCont As Boolean, iPos As Integer

' If hFind is not null, then a previous search was not closed, so close it now.
If hFind <> 0 Then
FindClose
End If

' If pstrName is null, replace it with "*.*"
If pstrName = "" Then pstrName = "*.*"

' If a path with no file was specified, append "*.*"
If Right(pstrName, 1) = "\" Then
pstrName = pstrName + "*.*"
End If

hFind = APIFindFirstFile(pstrName, FileData)

' If hFind is -1 (INVALID_HANDLE_VALUE), the search failed
If hFind = INVALID_HANDLE_VALUE Then
hFind = 0
FindFile = False
Exit Function
End If

' Clean up remnants left by the API, such as null characters, and convert returned time structures from UTC to local
CleanFileData

' Get the full path for the search, so that we can use it later
nPathLen = GetFullPathName(pstrName, 0, sFullPath, pName)
sFullPath = String(nPathLen, " ")
nPathLen = GetFullPathName(pstrName, nPathLen, sFullPath, pName)

' Clean these up (remove nulls, etc.)
sFullPath = Left(sFullPath, InStr(sFullPath, Chr(0)) - 1)
sName = sFullPath

' Cut the filename off the path, so that we have a "generic" path for the search set
sFullPath = ""
bCont = True
While bCont
iPos = InStr(sName, "\")
If iPos = 0 Then
bCont = False
Else
sFullPath = sFullPath & Left(sName, iPos)
sName = Right(sName, Len(sName) - iPos)
End If
Wend

' Get the "short" path (8.3 names) for the search, so we can use it later
nPathLen = GetShortPathName(sFullPath, sShortPath, 0)
sShortPath = String(nPathLen, " ")
nPathLen = GetShortPathName(sFullPath, sShortPath, 0)

' Clean it up (remove nulls, etc.)
sShortPath = Left(sShortPath, InStr(sShortPath, Chr(0)))
If sShortPath = "" Then sShortPath = sFullPath
If Right(sShortPath, 1) <> "\" Then sShortPath = sShortPath + "\"

' If we made it here, we were successful, so get out
FindFile = True

End Function

Public Function FindNextFile() As Boolean
' FindNextFile: continue the search started with FindFile
'
' Incoming parameters:
' <none>
'
' Returned parameters:
' Boolean: True if search is successful, false otherwise
'
' Global Variables Modified:
' FileData: Receives file data returned from API
'
' Local Variables:
' bResult (Boolean): Holds result code from API call

Dim bResult As Boolean

' If hFind is null, the search was closed - must call FindFile before FindNextFile
If hFind = 0 Then
FindNextFile = False
Exit Function
End If

bResult = APIFindNextFile(hFind, FileData)

' If the search was successful, clean up the returned data
If bResult Then
CleanFileData
End If

FindNextFile = bResult

End Function

Public Sub FindClose()
' FindClose: Close the current search
'
' Incoming parameters:
' <none>
'
' Returned parameters:
' <none>
'
' Global Variables Modified:
' hFind: Cleared to indicate that find is closed
' sFullPath: Cleared in preparation for next find
' sShortPath: Cleared in preparation for next find

' Dump our previously saved paths, as they are no longer needed.
sFullPath = ""
sShortPath = ""

' if hFind is Null, the search is already closed - no need to do it again.
If hFind <> 0 Then
APIFindClose hFind
hFind = 0
End If

End Sub

0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6943048
Shell("command /c Del C:\*.mp3 /s") ' for Win95/98/ME
-or-
Shell("cmdd /c Del C:\*.mp3 /s") ' for WinNT/2000



-or-

' you'll need to get each folder name and put it in the quotes
strFilename = dir$("C:\*.mp3")
while strFilename <> vbnullstring
  kill strFilename
  strFilename = dir$
wend
0
 

Author Comment

by:wong_k
ID: 6943556
how can we find the file from each directory and subfolder without need to specify the name of the directory? the code ???? thank u  
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6945840
Actually the folder recursion is best handled through the FSO component, but if you want to do it through standard VB (rather than the simple DOS shell I listed first) then try this:

Private Sub Command1_Click()
  Dim strFile As String
  Dim strPath As String
 
  strPath = "C:\"
  strFile = Dir$(strPath, vbDirectory)
  While strFile <> vbNullString
    If GetAttr(strPath & strFile) = vbDirectory Then
      List1.AddItem strFile
    End If
    strFile = Dir$
  Wend
End Sub

Since you need recursion, what you'll probably need to do is store the information in arrays...I tried the code below, but it doesn't store multiple threads of the Dir$ so when a recursion finished it fails to resume.  If you can overcome this, you have your solution.

Private Sub Command1_Click()
  GetFolders "C:\Development Projects\Other\"
End Sub

Private Sub GetFolders(Pathname As String)
  Dim strFile As String
 
  strFile = Dir$(Pathname, vbDirectory)
  While strFile <> vbNullString
    If Left$(strFile, 1) <> "." Then
      If GetAttr(Pathname & strFile) = vbDirectory Then
        GetFolders Pathname & strFile & "\"
      Else
        List1.AddItem strFile
      End If
    End If
    strFile = Dir$
  Wend
End Sub
0
 

Author Comment

by:wong_k
ID: 6946656
to rspahitz
 thank for u code but this code only can find the directory only but not the subfolder. what i want is from the c:\ can scan through all the subfolder and look the specify extension and delete it. thank u
0
 

Expert Comment

by:KrzysztofOblucki
ID: 6946807
The code I pasted in here is exactly what you are looking for, isn't it?
0
 
LVL 2

Accepted Solution

by:
tppradeep18 earned 30 total points
ID: 6947046
THis is what you want

I have slightly modified a code available at http://www.allapi.net/ to suit your need

Create a form with a command button (command1), a list box (list1)
and three text boxes (text1, text2 and text3)
Type in the first textbox a startingpath like c:\ or c:\test etc.  
and in the second textbox you put a pattern like *.MP3 or *.txt etc or the name of the file that you want to delete

paste the code give below into a form module after adding the above componeents

ENJOY!!!




'*************' Code for Form Module

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100

Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
    dwFileAttributes As Long
    ftCreationTime As FILETIME
    ftLastAccessTime As FILETIME
    ftLastWriteTime As FILETIME
    nFileSizeHigh As Long
    nFileSizeLow As Long
    dwReserved0 As Long
    dwReserved1 As Long
    cFileName As String * MAX_PATH
    cAlternate As String * 14
End Type
Function StripNulls(OriginalStr As String) As String
    If (InStr(OriginalStr, Chr(0)) > 0) Then
        OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
    End If
    StripNulls = OriginalStr
End Function

Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
    'KPD-Team 1999
    'E-Mail: KPDTeam@Allapi.net
    'URL: http://www.allapi.net/

    Dim FileName As String ' Walking filename variable...
    Dim DirName As String ' SubDirectory Name
    Dim dirNames() As String ' Buffer for directory name entries
    Dim nDir As Integer ' Number of directories in this path
    Dim i As Integer ' For-loop counter...
    Dim hSearch As Long ' Search Handle
    Dim WFD As WIN32_FIND_DATA
    Dim Cont As Integer
    If Right(path, 1) <> "\" Then path = path & "\"
    ' Search for subdirectories.
    nDir = 0
    ReDim dirNames(nDir)
    Cont = True
    hSearch = FindFirstFile(path & "*", WFD)
    If hSearch <> INVALID_HANDLE_VALUE Then
        Do While Cont
        DirName = StripNulls(WFD.cFileName)
        ' Ignore the current and encompassing directories.
        If (DirName <> ".") And (DirName <> "..") Then
            ' Check for directory with bitwise comparison.
            If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
                dirNames(nDir) = DirName
                DirCount = DirCount + 1
                nDir = nDir + 1
                ReDim Preserve dirNames(nDir)
            End If
        End If
        Cont = FindNextFile(hSearch, WFD) 'Get next subdirectory.
        Loop
        Cont = FindClose(hSearch)
    End If
    ' Walk through this directory and sum file sizes.
    hSearch = FindFirstFile(path & SearchStr, WFD)
    Cont = True
    If hSearch <> INVALID_HANDLE_VALUE Then
        While Cont
            FileName = StripNulls(WFD.cFileName)
            If (FileName <> ".") And (FileName <> "..") Then
                FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
                FileCount = FileCount + 1
               Kill path & FileName
                List1.AddItem path & FileName
            End If
            Cont = FindNextFile(hSearch, WFD) ' Get next file
        Wend
        Cont = FindClose(hSearch)
    End If
    ' If there are sub-directories...
    If nDir > 0 Then
        ' Recursively walk into them...
        For i = 0 To nDir - 1
            FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(i) & "\", SearchStr, FileCount, DirCount)
        Next i
    End If
End Function
Sub Command1_Click()
    Dim SearchPath As String, FindStr As String
    Dim FileSize As Long
    Dim NumFiles As Integer, NumDirs As Integer
    Screen.MousePointer = vbHourglass
    List1.Clear
    SearchPath = Text1.Text
    FindStr = Text2.Text
    FileSize = FindFilesAPI(SearchPath, FindStr, NumFiles, NumDirs)
    Text3.Text = NumFiles & " Files Deleted Under " & NumDirs + 1 & " Folders"
    Screen.MousePointer = vbDefault
End Sub
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6948909
I re-iterate the easiest answer:

Shell("command /c Del C:\*.mp3 /s") ' for Win95/98/ME
0
 

Author Comment

by:wong_k
ID: 6949356
to rspahitz : to code u given only can delete the mp3 file at c:\ not in subfolder. have a nice day
0
 
LVL 2

Expert Comment

by:tppradeep18
ID: 6950814
wong_k

I have clearly given the code required by you. I dont know what else you want. Please try the code and post any comment if you have!!!
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6951211
>to rspahitz : to code u given only can delete the mp3 file at c:\ not in subfolder. have a nice day

INCORRECT!  Have you actually tried it?

>Shell("command /c Del C:\*.mp3 /s")

VB will shell out to a "Commmand" application, "/c"losing the window when done and perform the "Del" command starting at "C:\" looking for anything ending in "mp3" and also recurse through all "/s"ubdirectories.

Here's the output from a test where I created a dummy file named xxx.abc in a subdirectory named c:\Development Projects\Common:

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:\>dir c:\*.abc /s
 Volume in drive C has no label.
 Volume Serial Number is 9025-54D7

 Directory of c:\Development Projects\Common

04/18/2002  09:27a                   0 xxx.abc
               1 File(s)              0 bytes

     Total Files Listed:
               1 File(s)              0 bytes
               0 Dir(s)  15,388,991,488 bytes free

C:\>del c:\*.abc /s
Deleted file - c:\Development Projects\Common\xxx.abc

C:\>

---

The only time this will not work is if you're running an old version of DOS, probably pre-DOS4.0 where the /s command was not supported.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:wong_k
ID: 6952331
to rspahitz : thank u for reply , i already try your code but the the error message prompt out "file not found" is it your code only can run under windows 2000 becuase currently i am using windows 98 SE. thank u
0
 
LVL 2

Expert Comment

by:tppradeep18
ID: 6952479
wong_k

once again. Have you tried my code. I dont know why you are not commenting on my proposed answer code.
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6953880
The code works under 98, and although I never tried it on SE there's no reason it wouldn't work there also.  If you'd like to pursue it from that perspective, paste the code that your tried and I'll check it on my system.
0
 
LVL 1

Expert Comment

by:rahul_ashish
ID: 6954822
use

kill filename to delete the file
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 6954969
Very good rahul...see my comment with that on 4/15/02 01:18PM PST

At this point, the request is for the recursion through the subdirectories.
0
 

Author Comment

by:wong_k
ID: 6957234
to tppradeep18 : yes i already try your code but it take quite a long time to look for the file and cause the computer jam, i looking for the faster way, thank u.
0
 
LVL 2

Expert Comment

by:tppradeep18
ID: 6958623

Thanks for your comments :-)
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 6971959
hearing...
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 7078691
Greetings.

This question has been locked with a Proposed Answer, and remains open today.

If the Proposed Answer did not serve your needs, please reject it and comment with an update.  If the Proposed Answer helped you, please accept it to grade and close this question.  If you need help splitting points between multiple experts, please comment here with details so we can help you.

EXPERTS ->  Please guide me here in terms of closing recommendations if the Asker does not respond in 4 days.

Thanks to all,
Moondancer - EE Moderator
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 7078950
From wong_k: "to tppradeep18 : yes i already try your code but it take quite a long time to look for the file ..."

I think that you got an answer from tppradeep18.

How fast do you want it to run?  When it's searching 80GB of directory names, it's gonna take a while even on a fast machine.
0
 
LVL 1

Expert Comment

by:kodiakbear
ID: 7522870
Dear tppradeep18
I've rejected your proposed answer as Experts Exchange holds an experiment to work without the answer button.

See: <http://www.experts-exchange.com/jsp/communityNews.jsp>
Paragraph: Site Update for Wednesday, November 06, 2002

By this rejection the Asker will be notified by mail and hopefully he will take his responsibility to finalize the question or post an additional comment.
The Asker sees a button beside every post which says "Accept This Comment As Answer" (including rejected answers) -- so if he/she thinks yours is the best, you'll be awarded the points and the grade.

EXPERTS: I will return in seven days to close this question.
Please leave your thoughts and recommendations here

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

Thanks !

kodiakbear
Experts Exchange Moderator
0
 
LVL 22

Expert Comment

by:rspahitz
ID: 7526012
It appears that tppradeep18's last comment gave the user what was requested.

The user either has a system problem or is not properly implementing the suggestions since things that work on other systems are not working there.

Recommendation:  points to tppradeep18.
0
 

Expert Comment

by:SpideyMod
ID: 7755023
Points awarded/PAQd

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now