Results 1 to 13 of 13

Thread: FSO: delete dir, its files and subdirs & write list to text file

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Resolved FSO: delete dir, its files and subdirs & write list to text file

    I am using VB6. I have a list of specific files that I need to delete from a Windows file system. I also have a list of directories (whose files and subdirectories can be deleted) that I need to delete.

    Even though I know which files and directories I need to delete, I need to be able to show a log of which files were actually deleted.

    I am using the FileSystemObject in the Microsoft Runtime Object Library. I know how to use the delete methods of the file and folder objects. I also know how to create a text file in the correct location in the file system.

    I need to have a list of all files which have been deleted (with the full path, file name and extension) written to a text file. I am having trouble getting the list written to a text file.

    I am listing the folders and files that need to be deleted like this:

    folderDelete "c:\Application\WcBcBarcode"
    folderDelete "c:\Program Files\WcBcBarcode"
    folderDelete "c:\Platform\WcBc"
    fileDelete "c:\Application\Startup\WcBcBarcode.exe"
    fileDelete "c:\Application\Startup\WcBcBarcode.lnk"
    fileDelete "c:\Application\WcBcBarcode.cpy

    the sub routines for folderDelete and fileDelete look like this:

    Sub fileDelete (fileName)
    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(fileName) Then objFSO.DeleteFile(fileName)
    EndSub

    Sub folderDelete (folderName)
    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FolderExists(folderName) Then objFSO.DeleteFolder(folderName)
    EndSub

    I thought that it would be easy to get the specified "files" into the text file by:
    1. declaring a file variable
    2. using the CreateTextFile method to specify the name and location for the text file
    3. using WriteLine or Write in a manner such as: WriteLine("Deleted: " & fileName)

    But I was not able to get it to work.

    And, for listing the files in the directories which were deleted, I thought that I should use GetFolder and pass the file names (and full paths) to an array, and then write the array to the text file.

    I was not able to get this to work, either.

    Can someone please help me to do the following:

    1. pass the file names of the files in the directories (and the directory paths themselves) which are being deleted to a list or an array. (shouldn't this happen in the deleteFolder sub routine?)
    2. write that list or array to the text file (shouldn't this happen in the deleteFolder sub routine?)
    3. write the list of specified files that are being deleted to the text file (shouldn't this happen in the deleteFile sub routine?)

    Your help is greatly appreciated.
    Last edited by tuonela; Dec 31st, 2007 at 04:33 PM. Reason: clarification

  2. #2
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: FSO: delete dir, its files and subdirs & write list to text file

    How are you calling the fileDelete and folderDelete functions? Can't you just add filenames to an array as you call them? Also, note that the FSO's .DeleteFolder method wipes out all the files and subdirectories in the folder. So, if you're logging you'll want to make sure the folder is empty before you wipe it.

  3. #3

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Re: FSO: delete dir, its files and subdirs & write list to text file

    I have the functions in the Form Load event.

    I have no way to tell if the directories are empty before I wipe it. This program will execute on 80 hand held devices which run a Windows OS. I will test it on a few at first, but I will not be able to manually inspect each device. I am on a plant site which spans 700-800 acres. The directories definitely do not have any files which shouldn't be deleted. I just have to be able to show the FDA how I know which files were deleted when they inspect the process.

    I am new at VB and I think I am building the array incorrectly. Also, I would not want to repeat the code over and over 20-30 times.

    Is there some code somewhere that I could see? I have googled this question for 10 or more hours today! lol

  4. #4
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: FSO: delete dir, its files and subdirs & write list to text file

    Try recursing through the directory structure and log directly to a file before you delete it. This should get you started:
    Code:
    Private oFSO As Scripting.FileSystemObject      'Some sort of public scope.
    
    Private Sub RecurseDelete(sFolder As String)
    
        Dim sFile As String, iFile As Integer
    
        Set oFSO = New Scripting.FileSystemObject
        If oFSO.FolderExists(sFolder) Then                      'Verify folder exists.
            sFile = "output.filename"                           '...or whatever the log file is.
            iFile = FreeFile                                    'Get a free file handle.
            Open sFile For Output As #iFile                     'Open it.
            Call DeleteFiles(oFSO.GetFolder(sFolder), iFile)    'Start having fun.
            Close #iFile                                        'Close the file.
        End If
        
        Set oFSO = Nothing
        
    End Sub
    
    Private Sub DeleteFiles(oFolder As Folder, iLogFile As Integer)
    
        Dim oSub As Folder, oFile As File
        
        For Each oFile In oFolder.Files                         'Loop through the files.
            Print #iLogFile, oFile.Name                         'Log them.
            oFile.Delete True                                   'Delete them.
        Next oFile
        
        For Each oSub In oFolder.SubFolders                     'Loop through the subfolders.
            Call DeleteFiles(oSub, iLogFile)                    'Recurse this function.
        Next oSub
        
        Print #iLogFile, oFolder.Name                           'Log the folder name.
        oFolder.Delete True                                     'Delete the folder.
    
    End Sub
    Last edited by Comintern; Dec 19th, 2007 at 10:40 PM. Reason: Fergot the folder logging.

  5. #5

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Re: FSO: delete dir, its files and subdirs & write list to text file

    Thank you I will try that today.

    Another question... will the name property give me the full path of the file as well as the file name in the text file?

    Just for kicks (now that I have access to my files at work), this is the code I have so far:

    Code:
    Private Sub Form_Load()
        Dim objFSO
        Dim filLog
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set filLog = objFSO.CreateTextFile("c:\testfile.txt", True)
            
        'center the form
        frmDelete.Top = (Screen.Height - frmDelete.Height) / 2
        frmDelete.Left = (Screen.Width - frmDelete.Width) / 2
        
        folderDelete "c:\junk"
        fileDelete "c:\test.txt"
        
        filLog.Close
    
    End Sub
    
    Sub fileDelete(fileName)
        Dim objFSO
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        objFSO.DeleteFile (fileName)
    End Sub
    
    Sub folderDelete(folderName)
        Dim objFSO
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        objFSO.DeleteFolder (folderName)
    End Sub
    Last edited by tuonela; Dec 20th, 2007 at 07:41 AM. Reason: Another question

  6. #6
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: FSO: delete dir, its files and subdirs & write list to text file

    Quote Originally Posted by tuonela
    Thank you I will try that today.

    Another question... will the name property give me the full path of the file as well as the file name in the text file?

    Just for kicks (now that I have access to my files at work), this is the code I have so far:
    Use the .Path property instead of the .Name property if you want the full filepath. Try this:
    Code:
    Private Sub Form_Load()
    
        Dim filLog As String, iFile As Integer
        
        Set oFSO = CreateObject("Scripting.FileSystemObject")       'Late bound.
        filLog = "c:\testfile.txt"
        iFile = FreeFile                                            'Get a free file handle.
        Open filLog For Output As #iFile                            'Open it.
        
        'center the form
        frmDelete.Top = (Screen.Height - frmDelete.Height) / 2
        frmDelete.Left = (Screen.Width - frmDelete.Width) / 2
        
        Call folderDelete("c:\junk", iFile)
        Call fileDelete("c:\test.txt", iFile)
        
        Close #iFile
    
        Set oFSO = Nothing
    
    End Sub
    
    Private Sub folderDelete(sFolder As String, iFile As Integer)
    
        If oFSO.FolderExists(sFolder) Then                      'Verify folder exists.
            Call DeleteFolder(oFSO.GetFolder(sFolder), iFile)   'Start having fun.
        End If
        
    End Sub
    
    Private Sub fileDelete(sFile As String, iFile As Integer)
    
        If oFSO.FileExists(sFile) Then                          'Verify file exists.
            Print #iFile, sFile                                 'Log the file.
            Kill sFile                                          'Delete it.
        End If
    
    End Sub
    
    Private Sub DeleteFolder(oFolder As Folder, iLogFile As Integer)
    
        Dim oSub As Folder, oFile As File
        
        For Each oFile In oFolder.Files                         'Loop through the files.
            Print #iLogFile, oFile.Path                         'Log them.
            oFile.Delete True                                   'Delete them.
        Next oFile
        
        For Each oSub In oFolder.SubFolders                     'Loop through the subfolders.
            Call DeleteFiles(oSub, iLogFile)                    'Recurse this function.
        Next oSub
        
        Print #iLogFile, oFolder.Path                           'Log the folder name.
        oFolder.Delete True                                     'Delete the folder.
    
    End Sub
    Note that for individual files you can just verify they exist and use the Kill statement.

  7. #7

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Re: FSO: delete dir, its files and subdirs & write list to text file

    When I try to debug, I get a compile error: User-defined type not defined. It doesn't like the type "Folder" and "File".

    I referenced the Microsoft Scripting Runtime. Is there something else I need to reference?

  8. #8
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: FSO: delete dir, its files and subdirs & write list to text file

    Quote Originally Posted by tuonela
    When I try to debug, I get a compile error: User-defined type not defined. It doesn't like the type "Folder" and "File".

    I referenced the Microsoft Scripting Runtime. Is there something else I need to reference?
    If you have a reference to the Scripting Runtime it should recognize them. Try explicitly casting them as Scripting.Folder and Scripting.File. Closing the project and re-opening it sometimes helps too.

  9. #9

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Re: FSO: delete dir, its files and subdirs & write list to text file

    I fixed it... I thought I had referenced the library, but hadn't.

    Looks like it works perfectly! Thanks!

    FYI... I did change something in the last sub routine "DeleteFolder". There was a call to DeleteFiles. I changed it to call to DeleteFolder.

  10. #10

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Re: FSO: delete dir, its files and subdirs & write list to text file

    UURRRGGGG! Wouldn't you know it... I was writing the program for Windows Mobile 2003 - I have to use .NET!!

    I have never programmed in .NET before. I hear it is very different. How much will this change the code?

  11. #11
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: FSO: delete dir, its files and subdirs & write list to text file

    Quote Originally Posted by tuonela
    UURRRGGGG! Wouldn't you know it... I was writing the program for Windows Mobile 2003 - I have to use .NET!!

    I have never programmed in .NET before. I hear it is very different. How much will this change the code?
    Structurally it shouldn't change it much. You'll have to convert the VB6 file handling (Open, Print, etc.) to either use the FSO or .NET file handling. Take the code I gave you and post it in the .NET area of the forum -- I'm sure you'll get some help over there.

  12. #12

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Smile Re: FSO: delete dir, its files and subdirs & write list to text file

    Great! Thanks so much for your help with this! It was very cool to see it work on my desktop machine!
    Last edited by tuonela; Dec 20th, 2007 at 02:17 PM. Reason: clarification

  13. #13

    Thread Starter
    New Member
    Join Date
    Dec 2007
    Location
    Virginia
    Posts
    11

    Resolved Re: FSO: delete dir, its files and subdirs & write list to text file

    Just thought I would post the code that finally worked for me:

    WORKS: VB.NET for Compact Framework 2.0 (SmartDevices - SDK)

    Code:
    Option Explicit On
    Option Strict On
    Imports System
    Imports System.IO
    Imports System.Security.Permissions
    
    Public Class frmDelete
        ' Inherit the System.Windows.Forms.Form Members
        Inherits System.Windows.Forms.Form
    
        'Declare variables for looping through files and folders in a directory
        Dim files As Long = 0
        Dim directories As Long = 0
    
        ' Make an instance of the StreamWriter
        Dim oWrite As System.IO.StreamWriter
    
        Private Sub frmDelete_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ' Open the text file
            oWrite = File.CreateText("\DeleteLog.txt")
    
            ' Call the DeleteFile Sub Routine
            Call DeleteFile("\test.txt")
    
            ' Call the DeleteFolder Sub Routine
            Call DeleteFolder("\junk")
    
            ' Close the text file
            oWrite.Close()
        End Sub
    
        Private Sub DeleteFile(ByRef fileName As String)
            ' Make sure the file exists
            If System.IO.File.Exists(fileName) = True Then
    
                ' Write the file to the text file
                oWrite.WriteLine(fileName)
    
                ' Delete the file
                System.IO.File.Delete(fileName)
            End If
        End Sub
    
        Private Sub DeleteFolder(ByRef folderName As String)
            ' Make sure the directory exists
            If System.IO.Directory.Exists(folderName) = True Then
    
                ' Write the directory to the test file
                oWrite.WriteLine(folderName)
    
                ' Call the SubFolders Sub Routine
                Call SubFolders(folderName)
    
                System.IO.Directory.Delete(folderName, True)
            End If
        End Sub
    
        Private Sub SubFolders(ByRef sFolder As String)
    
            Try
                ' Create a new DirectoryInfo object.
                Dim dir As New DirectoryInfo(sFolder)
    
                ' Check to see if the directory exists
                If Not dir.Exists Then
                    oWrite.WriteLine("The directory does not exist.")
                End If
    
                ' Call the GetFileSystemInfos method.
                Dim infos As FileSystemInfo() = dir.GetFileSystemInfos()
    
    
                ' Pass the result to the ListDirectoriesAndFiles
                ' method defined below.
                ListDirectoriesAndFiles(infos)
    
                ' Display the results to the console. 
                oWrite.WriteLine("Directories: {0}", directories)
                oWrite.WriteLine("Files: {0}", files)
    
                ' Catch any exceptions
            Catch e As Exception
                oWrite.WriteLine(e.Message)
            End Try
    
        End Sub
    
        Sub ListDirectoriesAndFiles(ByVal FSInfo() As FileSystemInfo)
            ' Check the FSInfo parameter.
            If FSInfo Is Nothing Then
                Throw New ArgumentNullException("FSInfo")
            End If
    
            ' Iterate through each item.
            Dim i As FileSystemInfo
            For Each i In FSInfo
    
                ' Check to see if this is a DirectoryInfo object.
                If TypeOf i Is DirectoryInfo Then
    
                    ' Add one to the directory count and add to the text file
                    directories += 1
                    oWrite.WriteLine(i.Name)
    
                    ' Cast the object to a DirectoryInfo object.
                    Dim dInfo As DirectoryInfo = CType(i, DirectoryInfo)
    
                    ' Iterate through all sub-directories.
                    ListDirectoriesAndFiles(dInfo.GetFileSystemInfos())
    
                    ' Check to see if this is a FileInfo object.
                ElseIf TypeOf i Is FileInfo Then
    
                    ' Add one to the file count and add directory to the text file
                    files += 1
                    oWrite.WriteLine(i.Name)
                End If
            Next i
    
        End Sub
    
    
    End Class

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