Results 1 to 12 of 12

Thread: VB - Files & Folders Module

  1. #1

    Thread Starter
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545

    VB - Files & Folders Module

    Hi,

    Here is a module I use with almost all of my applications. It allows you to easily work with files and folders, without using the FileSystemObject.

    Email me at clintolsen@rogers.com with any improvements or criticisms, or things you would like added!!!!!!

    P.S. I have posted the code here, but I've also attached the module in case you would like to use this. It's pretty straight forward to use, but I will post some examples of how to use the functions when i get home from work :-)

    (I had to break it up into 3 seperate posts, because it was too long )

    VB Code:
    1. '*******************************************************************************
    2. '*******************************************************************************
    3. '** Module:         modFile
    4. '**
    5. '** Purpose:        This module has a number of useful functions for working
    6. '**                 with files and folders.
    7. '**
    8. '** Created By:     Clint Olsen
    9. '** Last Modified:  05/08/2003
    10. '**
    11. '** CONTENTS
    12. '** ********
    13. '** FileExists()        - Determines if a file exists
    14. '** DirectoryExists()   - Determines if a directory exists
    15. '** PathAndFile()       - Concatenates a path and a filename
    16. '** CopyFiles()         - Copies files from a source to a destination directory
    17. '** CopyFile()          - Copies a file from a source to a destination directory
    18. '** MoveFile()          - Moves a file from a source to a destination path
    19. '** DeleteFile()        - Deletes the specified file
    20. '** CompareFiles()      - Checks if two files are the same (checks size and dates)
    21. '** CreateFile()        - Creates a file (for output) and returns the file number
    22. '** OpenFile()          - Opens an existing file (for input) and returns the file number
    23. '** CloseFile()         - Closes a file by file number
    24. '** GetFileTitle()      - Returns the file title for a given path (eg. testfile)
    25. '** GetFileName()       - Returns the file name for a given path (ex. testfile.txt)
    26. '** GetFilePath()       - Returns the location of the file in the given path (ex. C:\Temp\)
    27. '** WriteArrayToFile()  - Writes an array of strings to the specified file
    28. '** ReadArrayFromFile() - Reads a file and returns the contents as an array of strings
    29. '** MoveToRecycleBin()  - Moves a file to the recycling bin
    30. '*******************************************************************************
    31. '*******************************************************************************
    32.  
    33.  
    34. Option Explicit
    35.  
    36.  
    37. '*******************************************************************************
    38. '** MODULE DECLARATIONS
    39. '*******************************************************************************
    40. Public Type SHFILEOPSTRUCT
    41.     hwnd As Long
    42.     wFunc As Long
    43.     pFrom As String
    44.     pTo As String
    45.     fFlags As Integer
    46.     fAnyOperationsAborted As Long
    47.     hNameMappings As Long
    48.     lpszProgressTitle As Long
    49. End Type
    50.  
    51. Public Declare Function SHFileOperation Lib "shell32.dll" _
    52.     Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
    53.  
    54. Public Const FO_DELETE = &H3
    55. Public Const FOF_ALLOWUNDO = &H40
    56.  
    57.  
    58. '*******************************************************************************
    59. '** Function:   FileExists
    60. '** Parameters:
    61. '**     FilePath (String) - the full path of a file
    62. '** Returns: True if the file exists, false otherwise
    63. '*******************************************************************************
    64. Public Function FileExists(FilePath As String) As Boolean
    65.     If Len(FilePath) = 0 Then
    66.         FileExists = False
    67.     Else
    68.         If Len(Dir$(FilePath)) > 0 Then
    69.             FileExists = True
    70.         Else
    71.             FileExists = False
    72.         End If
    73.     End If
    74. End Function
    75.  
    76.  
    77. '*******************************************************************************
    78. '** Function:   DirectoryExists
    79. '** Parameters:
    80. '**     DirectoryPath (String) - the full path of a directory
    81. '** Returns: True if the directory exists, false otherwise
    82. '*******************************************************************************
    83. Public Function DirectoryExists(DirectoryPath As String) As Boolean
    84.     If Len(DirectoryPath) = 0 Then
    85.         DirectoryExists = False
    86.     Else
    87.         If Len(Dir$(DirectoryPath, vbDirectory)) > 0 Then
    88.             DirectoryExists = True
    89.         Else
    90.             DirectoryExists = False
    91.         End If
    92.     End If
    93. End Function
    94.  
    95.  
    96. '*******************************************************************************
    97. '** Function:   PathAndFile
    98. '** Parameters:
    99. '**     DirectoryPath (String) - the full path of a directory
    100. '**     FileName (String) - a file name
    101. '** Returns: The full file path and file name
    102. '*******************************************************************************
    103. Public Function PathAndFile(DirectoryPath As String, FileName As String) As String
    104.     If Right$(DirectoryPath, 1) = "\" Then
    105.         PathAndFile = DirectoryPath & FileName
    106.     Else
    107.         PathAndFile = DirectoryPath & "\" & FileName
    108.     End If
    109. End Function

    See next 2 posts, for more!
    Attached Files Attached Files

  2. #2

    Thread Starter
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    VB Code:
    1. '*******************************************************************************
    2. '** Function:   CopyFiles
    3. '** Parameters:
    4. '**     SourceDirectory (String) - the path of the source directory
    5. '**     DestinationDirectory (String) - the path of the destination directory
    6. '**     OverWrite (Optional Boolean) - indicates if we want to overwrite
    7. '**                                       any existing files if they exist
    8. '**     FileExtension (Optional String) - the file extension of the files to copy
    9. '** Returns: True if the copy procedure was successful, false otherwise
    10. '*******************************************************************************
    11. Public Function CopyFiles(SourceDirectory As String, DestinationDirectory As String, Optional OverWrite As Boolean = True, Optional FileExtension As String = "") As Boolean
    12.     On Error GoTo CopyFilesError
    13.      
    14.     Dim strFileName As String
    15.  
    16.     If Len(FileExtension) > 0 Then
    17.         'We are only copying files that contain the given file extension
    18.         strFileName = Dir$(PathAndFile(SourceDirectory, "") & "*." & FileExtension)
    19.         Do While Len(strFileName) > 0
    20.             If OverWrite = True Then
    21.                 'Copy the file to the destination directory
    22.                 Call FileCopy(PathAndFile(SourceDirectory, strFileName), PathAndFile(DestinationDirectory, strFileName))
    23.             Else
    24.                 'Only copy the file if it doesn't already exist
    25.                 If Len(Dir$(PathAndFile(DestinationDirectory, strFileName))) = 0 Then
    26.                     Call FileCopy(PathAndFile(SourceDirectory, strFileName), PathAndFile(DestinationDirectory, strFileName))
    27.                 End If
    28.             End If
    29.            
    30.             'Get the next file
    31.             strFileName = Dir$
    32.         Loop
    33.     Else
    34.         'We are copying all files
    35.         strFileName = Dir$(PathAndFile(SourceDirectory, ""))
    36.         Do While Len(strFileName) > 0
    37.             If OverWrite = True Then
    38.                 'Copy the file to the destination directory
    39.                 Call FileCopy(PathAndFile(SourceDirectory, strFileName), PathAndFile(DestinationDirectory, strFileName))
    40.             Else
    41.                 'Only copy the file if it doesn't already exist
    42.                 If Len(Dir$(PathAndFile(DestinationDirectory, strFileName))) = 0 Then
    43.                     Call FileCopy(PathAndFile(SourceDirectory, strFileName), PathAndFile(DestinationDirectory, strFileName))
    44.                 End If
    45.             End If
    46.            
    47.             'Get the next file
    48.             strFileName = Dir$
    49.         Loop
    50.     End If
    51.    
    52.     CopyFiles = True
    53.    
    54.     Exit Function
    55.    
    56. CopyFilesError:
    57.  
    58.     CopyFiles = False
    59.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    60.    
    61. End Function
    62.  
    63.  
    64. '*******************************************************************************
    65. '** Function:   CopyFile
    66. '** Parameters:
    67. '**     Source (String) - the path of the source file
    68. '**     Destination (String) - the path of the destination file
    69. '**     OverWrite (Optional Boolean) - indicates if we want to overwrite
    70. '**                                    the file if it already exists
    71. '** Returns: True if the copy procedure was successful, false otherwise
    72. '*******************************************************************************
    73. Public Function CopyFile(Source As String, Destination As String, Optional OverWrite As Boolean = True) As Boolean
    74.     On Error GoTo CopyFileError
    75.    
    76.     If OverWrite = True Then
    77.         Call FileCopy(Source, Destination)
    78.         CopyFile = True
    79.     Else
    80.         If Len(Dir$(Destination)) = 0 Then
    81.             Call FileCopy(Source, Destination)
    82.             CopyFile = True
    83.         Else
    84.             CopyFile = False
    85.         End If
    86.     End If
    87.    
    88.     Exit Function
    89.        
    90. CopyFileError:
    91.    
    92.     CopyFile = False
    93.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    94.    
    95. End Function
    96.  
    97.  
    98. '*******************************************************************************
    99. '** Function:   MoveFile
    100. '** Parameters:
    101. '**     Source (String) - the path of the source file
    102. '**     Destination (String) - the path of the destination file
    103. '**     OverWrite (Optional Boolean) - indicates if we want to overwrite
    104. '**                                    the file if it already exists
    105. '** Returns: True if the move procedure was successful, false otherwise
    106. '*******************************************************************************
    107. Public Function MoveFile(Source As String, Destination As String, Optional OverWrite As Boolean = False) As Boolean
    108.     On Error GoTo MoveFileError
    109.    
    110.     If OverWrite = True Then
    111.         If Len(Dir$(Destination)) > 0 Then
    112.             Kill Destination
    113.         End If
    114.         Name Source As Destination
    115.     Else
    116.         If Len(Dir$(Destination)) = 0 Then
    117.             Name Source As Destination
    118.         Else
    119.             MoveFile = False
    120.             Exit Function
    121.         End If
    122.     End If
    123.            
    124.        
    125.     MoveFile = True
    126.        
    127.     Exit Function
    128.    
    129. MoveFileError:
    130.    
    131.     MoveFile = False
    132.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description, vbExclamation, "Error Moving File"
    133.    
    134. End Function
    135.  
    136.  
    137. '*******************************************************************************
    138. '** Function:   CompareFiles (Quick and dirty comparing of files)
    139. '** Parameters:
    140. '**     FilePath1 (String) - the full path of the first file
    141. '**     FilePath2 (String) - the full path of the second file
    142. '** Returns: True if the files are exactly the same, false otherwise
    143. '*******************************************************************************
    144. Public Function CompareFiles(FilePath1 As String, FilePath2 As String)
    145.     If Len(Dir$(FilePath1)) = 0 Or Len(Dir$(FilePath2)) = 0 Then
    146.         CompareFiles = False
    147.     Else
    148.         Dim fileNumOne As Long
    149.         Dim fileNumTwo As Long
    150.        
    151.         'Compare the sizes of the files
    152.         fileNumOne = FreeFile
    153.         Open FilePath1 For Input As #fileNumOne
    154.        
    155.         fileNumTwo = FreeFile
    156.         Open FilePath2 For Input As #fileNumTwo
    157.        
    158.         If LOF(fileNumOne) = LOF(fileNumTwo) Then
    159.             CompareFiles = True
    160.         Else
    161.             CompareFiles = False
    162.             Exit Function
    163.         End If
    164.        
    165.         CloseFile (fileNumOne)
    166.         CloseFile (fileNumTwo)
    167.        
    168.         'Compare the file dates
    169.         If FileDateTime(FilePath1) = FileDateTime(FilePath2) Then
    170.             CompareFiles = True
    171.         Else
    172.             CompareFiles = False
    173.             Exit Function
    174.         End If
    175.        
    176.         'We are assuming that if the file sizes and creation dates are exactly
    177.         'the same, the files are exactly the same.
    178.         'If you need to add more checks, you can.
    179.     End If
    180. End Function

    See the next post for more!

  3. #3

    Thread Starter
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    VB Code:
    1. '*******************************************************************************
    2. '** Function:   CreateFile
    3. '** Parameters:
    4. '**     FilePath (String) - the full path of the file to be created
    5. '**     OverWrite (Optional Boolean) - determines if we want to overwrite
    6. '**                                       the file if it already exists
    7. '** Returns: The file number of the file, -1 if the file already exists and
    8. '**          OverWrite is false, -2 if any other error
    9. '*******************************************************************************
    10. Public Function CreateFile(FilePath As String, Optional OverWrite As Boolean = True) As Long
    11.     On Error GoTo CreateFileError
    12.    
    13.     If OverWrite = False Then
    14.         If Len(Dir$(FilePath)) <> 0 Then
    15.             CreateFile = -1
    16.             Exit Function
    17.         End If
    18.     End If
    19.     CreateFile = FreeFile
    20.     Open FilePath For Output As #CreateFile
    21.    
    22.     Exit Function
    23.    
    24. CreateFileError:
    25.    
    26.     CreateFile = -2
    27.          
    28. End Function
    29.  
    30.  
    31. '*******************************************************************************
    32. '** Function:   OpenFile
    33. '** Parameters:
    34. '**     FilePath (String) - the full path of the file to be created
    35. '** Returns: The file number of the file, -1 if it already exists,
    36. '**          -2 if any other error
    37. '*******************************************************************************
    38. Public Function OpenFile(FilePath As String) As Long
    39.     On Error GoTo OpenFileError
    40.    
    41.     If Len(Dir$(FilePath)) = 0 Then
    42.         OpenFile = -1
    43.         Exit Function
    44.     End If
    45.    
    46.     OpenFile = FreeFile
    47.     Open FilePath For Input As #OpenFile
    48.        
    49.     Exit Function
    50.    
    51. OpenFileError:
    52.  
    53.     OpenFile = -2
    54.        
    55. End Function
    56.  
    57.  
    58. '*******************************************************************************
    59. '** Function:   CloseFile
    60. '** Parameters:
    61. '**     FileNumber (Long) - the file number of the file to be closed
    62. '** Returns: True if the file was closed successfully, false otherwise
    63. '*******************************************************************************
    64. Public Function CloseFile(FileNumber As Long) As Boolean
    65.     On Error GoTo CloseFileError
    66.    
    67.     Close #FileNumber
    68.     CloseFile = True
    69.    
    70.     Exit Function
    71.  
    72. CloseFileError:
    73.  
    74.     CloseFile = False
    75.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    76.    
    77. End Function
    78.  
    79.  
    80. '*******************************************************************************
    81. '** Function:   DeleteFile
    82. '** Parameters:
    83. '**     FilePath (String) - the full file path of the file to be deleted
    84. '** Returns: True if the file was deleted successfully, false otherwise
    85. '*******************************************************************************
    86. Public Function DeleteFile(FilePath As String) As Boolean
    87.     On Error GoTo DeleteFileError
    88.    
    89.     If Len(Dir$(FilePath)) = 0 Then
    90.         'The file does not exist
    91.         DeleteFile = False
    92.     Else
    93.         Kill (FilePath)
    94.     End If
    95.    
    96.     DeleteFile = True
    97.    
    98.     Exit Function
    99.  
    100. DeleteFileError:
    101.    
    102.     DeleteFile = False
    103.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    104.    
    105. End Function
    106.  
    107.  
    108. '*******************************************************************************
    109. '** Function:   GetFileTitle
    110. '** Parameters:
    111. '**     FilePath (String) - the full file path of the file to be deleted
    112. '** Returns: The file title for the given file path
    113. '*******************************************************************************
    114. Public Function GetFileTitle(FilePath As String) As String
    115.     On Error GoTo GetFileTitleError
    116.  
    117.     Dim slashLocation As Integer
    118.     Dim dotLocation As Integer
    119.    
    120.     If Len(FilePath) = 0 Then
    121.         GetFileTitle = ""
    122.         Exit Function
    123.     End If
    124.    
    125.     'Find the last \ in the path
    126.     slashLocation = InStrRev(FilePath, "\")
    127.    
    128.     'Retrieve the . location
    129.     dotLocation = InStrRev(FilePath, ".")
    130.     If dotLocation = 0 Then dotLocation = Len(FilePath) + 1
    131.        
    132.     GetFileTitle = Mid$(FilePath, slashLocation + 1, dotLocation - slashLocation - 1)
    133.    
    134.     Exit Function
    135.    
    136. GetFileTitleError:
    137.    
    138.     GetFileTitle = ""
    139.     MsgBox "Error #" & Err.numer & vbCrLf & Err.Description, vbExclamation, "Error"
    140.    
    141. End Function
    142.  
    143.  
    144. '*******************************************************************************
    145. '** Function:   GetFileName
    146. '** Parameters:
    147. '**     FilePath (String) - the full file path of the file
    148. '** Returns: The file name of for the given file path
    149. '*******************************************************************************
    150. Public Function GetFileName(FilePath As String) As String
    151.     On Error GoTo GetFileNameError
    152.    
    153.     Dim slashLocation As Integer
    154.    
    155.     If Len(FilePath) = 0 Then
    156.         GetFileName = ""
    157.         Exit Function
    158.     End If
    159.        
    160.     'Find the last \ in the path
    161.     slashLocation = InStrRev(FilePath, "\")
    162.    
    163.     GetFileName = Mid$(FilePath, slashLocation + 1, Len(FilePath) + 1 - slashLocation)
    164.        
    165.     Exit Function
    166.  
    167. GetFileNameError:
    168.    
    169.     GetFileName = ""
    170.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description, vbExclamation, "Error"
    171.    
    172. End Function
    173.  
    174.  
    175. '*******************************************************************************
    176. '** Function:   GetFilePath
    177. '** Parameters:
    178. '**     FilePath (String) - the full file path of the file
    179. '** Returns: The path of the file in the given file path
    180. '*******************************************************************************
    181. Public Function GetFilePath(FilePath As String) As String
    182.     On Error GoTo GetFilePathError
    183.    
    184.     Dim slashLocation As Integer
    185.    
    186.     If Len(FilePath) = 0 Then
    187.         GetFilePath = ""
    188.         Exit Function
    189.     End If
    190.    
    191.     'Find the last \ in the path
    192.     slashLocation = InStrRev(FilePath, "\")
    193.    
    194.     If slashLocation = 0 Then
    195.         GetFilePath = ""
    196.     Else
    197.         GetFilePath = Mid$(FilePath, 1, slashLocation)
    198.     End If
    199.    
    200.     Exit Function
    201.  
    202. GetFilePathError:
    203.    
    204.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description, vbExclamation, "Error"
    205.    
    206. End Function
    207.  
    208.  
    209. '*******************************************************************************
    210. '** Function:   WriteArrayToFile
    211. '** Parameters:
    212. '**     strArray (String) - an array of strings to write to the file
    213. '**     FilePath (String) - the path of the file to write to
    214. '** Returns: True if writing the array to file was successful, false otherwise
    215. '*******************************************************************************
    216. Public Function WriteArrayToFile(strArray() As String, FilePath As String) As Boolean
    217.     On Error GoTo WriteArrayToFileError
    218.      
    219.     Dim minItem As Long, maxItem As Long
    220.     Dim i As Integer
    221.    
    222.     Dim fileNum As Long
    223.     fileNum = CreateFile(FilePath)
    224.    
    225.     minItem = LBound(strArray)
    226.     maxItem = UBound(strArray)
    227.    
    228.     For i = minItem To maxItem
    229.         Print #fileNum, strArray(i)
    230.     Next i
    231.    
    232.     CloseFile (fileNum)
    233.    
    234.     WriteArrayToFile = True
    235.    
    236.     Exit Function
    237.  
    238. WriteArrayToFileError:
    239.    
    240.     WriteArrayToFile = False
    241.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    242.    
    243. End Function
    244.  
    245.  
    246. '*******************************************************************************
    247. '** Function:   ReadArrayFromFile
    248. '** Parameters:
    249. '**     FilePath (String) - the file path of the file to read the array from
    250. '** Returns: An array of strings
    251. '*******************************************************************************
    252. Public Function ReadArrayFromFile(FilePath As String) As String()
    253.     Dim strArray() As String
    254.     Dim itemCount As Long
    255.     Dim fileNum As Long
    256.    
    257.     itemCount = -1
    258.    
    259.     fileNum = OpenFile(FilePath)
    260.    
    261.     If fileNum = -2 Then
    262.         Exit Function
    263.     End If
    264.    
    265.     Do While Not EOF(fileNum)
    266.         itemCount = itemCount + 1
    267.         ReDim Preserve strArray(itemCount)
    268.         Input #fileNum, strArray(itemCount)
    269.     Loop
    270.    
    271.     CloseFile (fileNum)
    272.    
    273.     ReadArrayFromFile = strArray
    274.    
    275.     Exit Function
    276.  
    277. ReadArrayFromFileError:
    278.  
    279.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description, vbExclamation, "Error"
    280.    
    281. End Function
    282.  
    283.  
    284. '*******************************************************************************
    285. '** Function:   MoveToRecycleBin
    286. '** Parameters:
    287. '**     FilePath (String) - the file path of the file to read the array from
    288. '** Returns: An array of strings
    289. '*******************************************************************************
    290. Public Function MoveToRecycleBin(FilePath As String)
    291.     On Error GoTo MoveToRecycleBinError
    292.  
    293.     'strfile is the full path of the file you want to put in the recycle bin
    294.     Dim SHop As SHFILEOPSTRUCT
    295.     With SHop
    296.         .wFunc = FO_DELETE
    297.         .pFrom = FilePath
    298.         .fFlags = FOF_ALLOWUNDO
    299.     End With
    300.     SHFileOperation SHop
    301.    
    302.     MoveToRecycleBin = True
    303.    
    304.     Exit Function
    305.  
    306. MoveToRecycleBinError:
    307.    
    308.     MoveToRecycleBin = False
    309.     MsgBox "Error #" & Err.Number & vbCrLf & Err.Description
    310.    
    311. End Function

  4. #4

    Thread Starter
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    VB Code:
    1. '************************************************
    2. '** HOW TO USE THESE FUNCTIONS
    3. '************************************************
    4.  
    5.     '*************************************************************
    6.     'How to use FileExists()
    7.     '*************************************************************
    8.     Dim strFileName As String
    9.     strFileName = "C:\Temp\testfile.txt"
    10.    
    11.     If FileExists(strFileName) Then
    12.         'The file exists
    13.        
    14.     Else
    15.         'The file doesn't exist!
    16.  
    17.     End If
    18.    
    19.     '*************************************************************
    20.     'How to use DirectoryExists()
    21.     '*************************************************************
    22.     Dim strFolderName As String
    23.     strFolderName = "C:\Temp\"
    24.    
    25.     If DirectoryExists(strFolderName) Then
    26.         'The folder exists
    27.        
    28.     Else
    29.         'The folder does not exist
    30.        
    31.     End If
    32.    
    33.     '*************************************************************
    34.     'How to use PathAndFile()
    35.     'NOTE: I use this function because App.Path usually returns a
    36.     'backslash if your program is running on C:\, but if you run
    37.     'your program from a folder inside, such as C:\Temp it does not
    38.     'return a backslash at the end
    39.     '
    40.     'I also use this in other places in my code to prevent mistakes
    41.     'from omitting a slash by accident!
    42.     '*************************************************************
    43.     Dim strFileName As String
    44.     'Ensure that we get the correct application path
    45.     strFileName = PathAndFile(App.Path, "data.txt")
    46.    
    47.     '*************************************************************
    48.     'How to use CopyFiles()
    49.     '*************************************************************
    50.     Dim blnSuccess As Boolean
    51.    
    52.     'To copy ALL files and overwrite them
    53.     blnSuccess = CopyFiles("C:\Temp\Test1\", "C:\Temp\Test2\")
    54.    
    55.     'To copy ALL files WITHOUT overwriting any
    56.     blnSuccess = CopyFiles("C:\Temp\Test1\", "C:\Temp\Test2", False)
    57.    
    58.     'To copy ALL txt files overwriting any existing files
    59.     blnSuccess = CopyFiles("C:\Temp\Test1\", "C:\Temp\Test2", True, "txt")
    60.    
    61.     If blnSuccess Then
    62.         'The copy procedure was successful
    63.        
    64.     Else
    65.         'The copy procedure was NOT successful
    66.        
    67.     End If
    68.    
    69.     '*************************************************************
    70.     'How to use CopyFile()
    71.     '*************************************************************
    72.     Dim blnSuccess As Boolean
    73.    
    74.     'To copy a file, overwriting it if it already exists
    75.     blnSuccess = CopyFile("C:\Temp\Test1\test1.txt", "C:\Temp\Test2\test1.txt")
    76.    
    77.     'To copy a file, WITHOUT overwriting it if it already exists
    78.     blnSuccess = CopyFile("C:\Temp\Test1\test1.txt", "C:\Temp\Test2\test1.txt", False)
    79.    
    80.     If blnSuccess Then
    81.         'The copy procedure was successful
    82.        
    83.     Else
    84.         'The copy procedure was successful
    85.        
    86.     End If
    87.    
    88.     '*************************************************************
    89.     'How to use MoveFile()
    90.     '*************************************************************
    91.     'Same as CopyFile, except it deletes the source file after copying
    92.    
    93.     '*************************************************************
    94.     'How to use CompareFiles()
    95.     'NOTE: All this does is check the file sizes, and dates,
    96.     '      so it is potentially still possible for files to be different
    97.     '*************************************************************
    98.     Dim blnSuccess As Boolean
    99.    
    100.     blnSuccess = CompareFiles("C:\Temp\file1.txt", "C:\Temp\file2.txt")
    101.     If blnSuccess = True Then
    102.         'THe files are the same!
    103.        
    104.     Else
    105.         'The files are NOT the same!
    106.    
    107.     End If
    108.        
    109.     '*************************************************************
    110.     'How to use CreateFile()
    111.     'NOTE: I use this function every time I need to create a file
    112.     '      for output.  It allows you to avoid calling FreeFile
    113.     '      each time
    114.     '*************************************************************
    115.     Dim fileNumber As Long
    116.     fileNumber = CreateFile("C:\Temp\testfile.txt")
    117.    
    118.     'If you need to check to make sure the file was created
    119.     'do it like this
    120.     If fileNumber < 0 Then
    121.         'An error occured and the file was not created!
    122.        
    123.     Else
    124.         'The file was created successfully
    125.        
    126.     End If
    127.    
    128.     '*************************************************************
    129.     'How to use OpenFile()
    130.     'NOTE: This function is used to open a file for input
    131.     '*************************************************************
    132.     Dim fileNumber As Long
    133.     fileNumber = OpenFile("C:\Temp\testfile.txt")
    134.    
    135.     'If you need to check to make sure the file was opened
    136.     'successfully, do it like this
    137.     If fileNumber < 0 Then
    138.         'An error occured and the file was not opened!
    139.        
    140.     Else
    141.         'The file was created successfully
    142.        
    143.     End If
    144.    
    145.        
    146.     '*************************************************************
    147.     'How to use CloseFile()
    148.     '*************************************************************
    149.     Dim fileNumber As Long
    150.     fileNumber = OpenFile("C:\Temp\testfile.txt")
    151.    
    152.     'do your stuff here
    153.    
    154.     CloseFile (fileNumber)
    155.    
    156.    
    157.     '*************************************************************
    158.     'How to use DeleteFile()
    159.     '*************************************************************
    160.     Dim blnSuccess As Boolean
    161.    
    162.     blnSuccess = DeleteFile("C:\Temp\testfile.txt")
    163.    
    164.     If blnSuccess Then
    165.         'The file was deleted successfully
    166.        
    167.     Else
    168.         'The file was not deleted!
    169.        
    170.     End If
    171.    
    172.     '*************************************************************
    173.     'How to use GetFileTitle()
    174.     'Note: This returns the file title only
    175.     '      Example: For C:\Temp\testfile.txt it returns testfile
    176.     '*************************************************************
    177.     Dim strFileName As String
    178.     Dim strFileTitle As String
    179.  
    180.     strFileName = "C:\Temp\testfile.txt"
    181.     strFileTitle = GetFileTitle(strFileName)
    182.    
    183.     '*************************************************************
    184.     'How to use GetFileName()
    185.     'Note: This returns the file name (with extension)
    186.     '      Example: For C:\temp\testfile.txt it returns testfile.txt
    187.     '*************************************************************
    188.     Dim strFileName As String
    189.     Dim strFileNameOnly As String
    190.  
    191.     strFileName = "C:\Temp\testfile.txt"
    192.     strFileNameOnly = GetFileName(strFileName)
    193.    
    194.     '*************************************************************
    195.     'How to use GetFilePath()
    196.     'Note: This returns the file path only
    197.     '      Example: For C:\Temp\testfile.txt it returns C:\Temp\
    198.     '*************************************************************
    199.     Dim strFileName As String
    200.     Dim strFilePath As String
    201.  
    202.     strFileName = "C:\Temp\testfile.txt"
    203.     strFilePath = GetFilePath(strFileName)
    204.    
    205.     '*************************************************************
    206.     'How to use WriteArrayToFile()
    207.     '*************************************************************
    208.     Dim strArr(3) As String
    209.     strArr(0) = "Test 1"
    210.     strArr(1) = "Test 2"
    211.     strArr(2) = "Test 3"
    212.     strArr(3) = "Test 4"
    213.    
    214.     blnSuccess = WriteArrayToFile(strArr, "C:\Temp\output.txt")
    215.    
    216.     If blnSuccess Then
    217.         'The array was successfully written to the file
    218.        
    219.     Else
    220.         'The array was not written to the file!
    221.    
    222.     End If
    223.    
    224.     '*************************************************************
    225.     'How to use ReadArrayFromFile()
    226.     '*************************************************************
    227.     Dim strArr() As String
    228.    
    229.     strArr = ReadArrayFromFile("C:\Temp\output.txt")
    230.    
    231.     '*************************************************************
    232.     'How to use MoveToRecycleBin()
    233.     '*************************************************************
    234.     Dim strFileName As String
    235.    
    236.     blnSuccess = MoveToRecycleBin(strFileName)
    237.    
    238.     If blnSuccess = True Then
    239.         'The file was sent to the recycling bin
    240.        
    241.     Else
    242.         'The file was NOT sent to the recycling bin
    243.        
    244.     End If

  5. #5
    Fanatic Member seec77's Avatar
    Join Date
    Jan 2003
    Posts
    596
    great module dude!
    Best Regards,
    seec77

    If you helped me, cosinder yourself thanked.

    Get each and every Garfield strip here!
    Here you can get all Calvin & Hobes strips!
    Damn UComics! It was probably unprofitable for them to allow us to just download Garfield and Calving & Hobes strips... so they made folder indexing unallowed on their server!!!

    I am 33% addicted to Counterstrike. What about you?
    I am 23% addicted to Star Wars. What about you?
    I am 0% addicted to Tupac. What about you?

  6. #6
    Lively Member xing's Avatar
    Join Date
    Jun 2003
    Location
    In front of my PC
    Posts
    72

    Thumbs up thanks

    geez..just what i needed. thanks for posting this module.

  7. #7
    Hyperactive Member phrozeman's Avatar
    Join Date
    Apr 2000
    Location
    Netherlands
    Posts
    442
    Damn nice peace of work, saves me allot of time
    There's a certain mystique when I speak, that you notice that it's sorta unique, cause you know it's me

  8. #8

    Thread Starter
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    I'm glad you all have found this useful, cuz I sure have many times. Is there any other functions I can add to make it better?

  9. #9
    Fanatic Member seec77's Avatar
    Join Date
    Jan 2003
    Posts
    596
    i think you should change the folder exists and file exists functions to use the api's (don't remember them off the top of my head...)! imho this way sucks!
    Best Regards,
    seec77

    If you helped me, cosinder yourself thanked.

    Get each and every Garfield strip here!
    Here you can get all Calvin & Hobes strips!
    Damn UComics! It was probably unprofitable for them to allow us to just download Garfield and Calving & Hobes strips... so they made folder indexing unallowed on their server!!!

    I am 33% addicted to Counterstrike. What about you?
    I am 23% addicted to Star Wars. What about you?
    I am 0% addicted to Tupac. What about you?

  10. #10
    Fanatic Member
    Join Date
    Jan 2001
    Posts
    574
    Looks nice. I've got a little addition (or change). It is about files comparing. Not just by the filesize and filedate
    Just take a look at it, i've uploaded it to Planet Source Code

    http://www.pscode.com/vb/scripts/Sho...46558&lngWId=1

    Also your fileexists is a little improved.
    Don't Hate Me Cause You Ain't Me

  11. #11
    Addicted Member
    Join Date
    Mar 2001
    Location
    Greece
    Posts
    164

    Here's a nice addition to your module

    Code:
    Function SeparatePath(Path As String, Optional ReturnMode As Integer = 1) As String
        'Input : a file path
        'ReturnMode=1  : returns directory (with trailing '\')
        'ReturnMode=2  : returns filename+extension
        'ReturnMode=3  : returns filename only
        'ReturnMode=4  : returns extension only
        
        Dim nPos1 As Long
        Dim nPos2 As Long
        Dim sTemp As String
        
        Select Case ReturnMode
        Case 1 'get directory
            'search for '\'
            nPos2 = InStrRev(Path, "\")
            If nPos2 > 0 Then
                nPos1 = 1
                SeparatePath = Mid(Path, nPos1, nPos2 - nPos1 + 1)
            Else
                'search for ':' if '\' not found
                nPos2 = InStrRev(Path, ":")
                If nPos2 > 0 Then
                    'found drive letter
                    nPos1 = 1
                    SeparatePath = Mid(Path, nPos1, nPos2 - nPos1 + 1)
                Else
                    'no directory found
                    SeparatePath = vbNullString
                End If
            End If
        Case 2  'get complete filename
            'call function again to find directory length
            nPos1 = Len(SeparatePath(Path, 1))
            nPos1 = nPos1 + 1
            nPos2 = Len(Path)
            SeparatePath = Mid(Path, nPos1, nPos2 - nPos1 + 1)
        Case 3  'get filename only
            'call function again to find complete filename
            sTemp = SeparatePath(Path, 2)
            nPos1 = 1
            nPos2 = InStrRev(sTemp, ".")
            If nPos2 > 0 Then
                nPos2 = nPos2 - 1
            Else
                nPos2 = Len(sTemp)
            End If
            SeparatePath = Mid(sTemp, nPos1, nPos2 - nPos1 + 1)
        Case 4  'get filename extension only
            'call function again to find complete filename
            sTemp = SeparatePath(Path, 2)
            nPos1 = InStrRev(sTemp, ".")
            If nPos1 > 0 Then
                nPos1 = nPos1 + 1
                nPos2 = Len(sTemp)
                SeparatePath = Mid(sTemp, nPos1, nPos2 - nPos1 + 1)
            Else
                SeparatePath = vbNullString
            End If
        End Select
    End Function
    --hyperspaced

  12. #12
    Frenzied Member
    Join Date
    Dec 2008
    Location
    Melbourne Australia
    Posts
    1,487

    Re: VB - Files & Folders Module

    How about including MoveFiles
    Say this folder c:\MoveFrom exists (and contains some files)
    And you want to move all the files to another folder c:\MoveTo
    This code will accomplish that by using the Name function to rename 'MoveFrom' to 'MoveTo' (Files are now in 'MoveTo')
    Then use mkdir to recreate 'MoveFrom' (which will now be empty).

    Code:
    'Have txtFrom textbox on the form containing 'C:\MoveFrom'
    'Have txtTo   textbox on the form containing 'C:\Moveto'
    'Have command button cmdMove
    
    Private Sub cmdMove_Click()
     Dim sFrom As String
     Dim sTo As String
        sFrom = txtFrom.Text  'From folder which can contain files
        sTo = txtTo.Text      'To folder which will inherit the files that were within the From folder
        Name sFrom As sTo     'Rename the From folder to the To folder name
        DoEvents
        MkDir sFrom           'Re-make the From Folder (which now will be empty)
    End Sub
    Rob
    PS I am about to use this in in a larger program, which is the only program that uses the 'MoveTo' folder, so it is in full control of it's existence.
    Other usage, may need some error checking built in.
    Last edited by Bobbles; May 29th, 2019 at 10:54 PM. Reason: explain why no error checking

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