Está en la página 1de 13

File Handling And FSO Object

The File System Object (FSO) enables you to manipulate the files, folders and drives as well as read and write to sequential files. Before using the FSO, you have to add the "Microsoft Scripting Runtime Library" to the current project by selecting "Project", "References" from the menu bar. Alternatively you can use the CreateObject function to create the reference at run-time.
Set fso = CreateObject("Scripting.FileSystemObject")

EXAMPLE PROGRAMS:
The following example programs illustrate how to use the File System Object. Listing subdirectories Recursively Setting Attributes Loading subdirectories into the TreeView control

FILE SYSTEM OBJECT: There are five types of File System Object. 1. 2. 3. 4. 5. File. Folder. Drive. TextStream. Random Access Files.

The FileSystemObject is used to manipulate the files, folders and directories. The following is a list of some of the methods avaiable to the FileSystemObject.

File System Object Methods

1

Used to create a folder. Used to return the name of the parent folder. Used to return a specified drive. Used to determine whether a file exists. Used to create and return a string representing a file name. Used to move a folder. Used to copy an existing folder. Used to move a file.Name & vbCrLf 2 . Used to determine whether a folder exists. Used to delete a file. Used to return a specified folder. Used to determine whether a drive exists. The FSO File Object The following uses some of the FSO File's properties to display information about a file. Used to delete a folder. Used to return the drive name. Used to create a text file. Used to open an existing text file. Used to return a specified file. Used to return the full path name.GetFile(fileName) strInfo = fileSpec. Private Sub displayFileInfo(ByVal fileName As String) Dim fso As New FileSystemObject Dim fileSpec As File Dim strInfo As String Set fileSpec = fso.Method CopyFile CopyFolder CreateFolder CreateTextFile DeleteFile DeleteFolder DriveExists FileExists FolderExists GetAbsolutePathNa me GetDrive GetDriveName GetFile GetFileName GetFolder GetParentFolderNa me GetTempName MoveFile MoveFolder OpenTextFile Description Used to copy an existing file. Used to return the file name.

DateCreated & vbCrLf strInfo = strInfo & "Last Accessed: " strInfo = strInfo & fileSpec. Delete. and openAsTextStream methods are available for the FSO File object. drv As Drive Dim strInfo As String.drives On Error Resume Next For Each drv In connectedDrives strInfo = strInfo & drv.DateCreated & vbCrLf strInfo = strInfo & "Size: " strInfo = strInfo & folderSpec. vbInformation.Size MsgBox strInfo.DateLastAccessed & vbCrLf strInfo = strInfo & "Last Modified: " strInfo = strInfo & fileSpec. Delete. Dim fso As New FileSystemObject Dim connectedDrives As drives. CreateTextFile. THE FSO DRIVE OBJECT The following example iterates through the Drives collection and writes the drive name for each drive found.GetFolder(folderName) strInfo = folderSpec.DriveLetter & ": " ' Check if the drive is shared If drv. driveName As String Set connectedDrives = fso. Private Sub displayFolderInfo(ByVal folderName As String) Dim fso As New FileSystemObject Dim folderSpec As Folder Dim strInfo As String Set folderSpec = fso. "File Information" Set fileSpec = Nothing End Sub The Copy.strInfo = strInfo & "Created: " strInfo = strInfo & fileSpec.Name & vbCrLf strInfo = strInfo & "Created: " strInfo = strInfo & folderSpec. and Move methods are available for the FSO Folder object.DateLastModified MsgBox strInfo. Move.DriveType = 3 Then 3 . The FSO Folder Object The following uses some of the FSO Folder's properties to display information about a folder. "Folder Information" Set folderSpec = Nothing End Sub The Copy. vbInformation.

FreeSpace If drv. the WriteBlankLine method is used to write blank lines and the WriteLine method is used to write a line of text ending with a newline character.IsReady Then strInfo = strInfo & " ready" & vbCrLf Else strInfo = strInfo & " not ready" & vbCrLf End If Next drv MsgBox strInfo. ForReading or ForWriting. fsoStream.WriteLine "First line in the text file. vbInformation. The Write method is used to write a string. "Connected Drives" Set connectedDrives = Nothing Set fso = Nothing The FSO TextStream Object The FSO TextStream object is used to read and write to sequential text files.ShareName driveName = drv.Else driveName = drv. overwrite an existing file or append text to the end of an existing file. WRITING TEXT FILES When writing to a file." The FSO TextStream CreateTextFile Method 4 .Write "Hello" fsoStream. you can either create a new file. The FSO File object's OpenAsTextStream method may be used to open a TextStream ForAppending.VolumeName End If strInfo = strInfo & driveName strInfo = strInfo & " Free space: " & drv. The CreateTextFile method is used to create a text file and return a reference to a TextStream object.WriteBlankLines 2 fsoStream.

This is not advisable for large files as it's a waste of memory.WriteLine "Appending line to the text file" fsoStream.Close Set fsoStream = Nothing Set fso = Nothing READING TEXT FILES The FSO File object's OpenAsTextFile(ForReading) is used to open a text file for reading.GetFile("c:\junk\junk.The following example creates a text file using the CreateTextFile method. Text written to the file is appended to the end. ReadAll and ReadLine methods are used to read from the text file. 5 . Dim fso As New FileSystemObject Dim fsoStream As TextStream ' Create a text file.Close Set fsoStream = Nothing Set fso = Nothing APPENDING TO THE END OF A TEXTSTREAM To append to a file.txt".WriteBlankLines 2 fsoStream. The CreateTextFile method takes as parameters the filename to be created and a Boolean value indicating whether the file should be overwritten if it exists.txt") Set fsoStream = f. The Read.WriteLine "First line in the text file." fsoStream. open the TextStream using the ForAppending parameter. The Read method takes as a parameter the number of characters to be read. Dim fso As New FileSystemObject Dim f As File Dim fsoStream As TextStream Set f = fso. The ReadAll method reads the whole text file." fsoStream. and return a reference to a TextStream Set fsoStream = fso.OpenAsTextStream(ForAppending) ' Append lines to the file fsoStream. True) ' Write to the file fsoStream.CreateTextFile("c:\junk\junk. The default value is True.WriteLine "Line after two blank lines.

ReadAll lineText = fsoStream.ReadLine Debug.Read(1) wholeFile = fsoStream.The ReadLine method reads one line of text from the file.OpenAsTextStream(ForReading) ' Read the file line by line.Close Set fsoStream = Nothing Set f = Nothing Set fso = Nothing Example Programs The following examples all use the FSO Object. and the SkipLine method is used to skip a whole line. • • • • Listing subdirectories Recursively Setting Attributes Loading subdirectories into the TreeView control List subdirectories recursively The following example iterates through directories recursively writing the name to a MultiLine TextBox.ReadLine The Skip(n) method may be used to skip n characters.txt") Set fsoStream = f. The AtEndOfStream property may be used to test for the end of file.AtEndOfStream strLine = fsoStream. READING EXAMPLE: To read a file. Option Explicit Private Sub dirFiles_Change() Dim fso As New FileSystemObject. Dim fso As New FileSystemObject Dim f As File Dim fsoStream As TextStream Dim strLine As String Set f = fso. printing the results to the Form Do While Not fsoStream. singleChar = fsoStream. open the TextStream using the ForReading parameter.Print strLine Loop fsoStream. and the AtEndOfLine property may be used to for the end of a line. The number of directories found and the total size is written as a summary at the end. startFolder As Folder 6 .GetFile("c:\junk\junk.

Path) > 3 Then txtDisplay. Option Explicit Private Sub cmdAttributes_Click() 7 .##0") txtDisplay.Text = txtDisplay. True) Next subFolder Next currentFolder displayFolder = folderCount Set rootFolder = Nothing Set fso = Nothing End Function SETTING ATTRIBUTES: The following example sets the file attributes for all files meeting a specified file pattern in a directory.Text & currentFolder & vbCrLf folderCount = folderCount + 1 For Each subFolder In currentFolder.SubFolders folderCount = folderCount + displayFolder(subFolder.Text = txtDisplay.Dim numFolders As Integer Dim strStart As String.Path ' Avoid root directories as it's likely to run out of memory If Len(dirFiles. ByVal firstTime As Boolean) As Integer Dim fso As New FileSystemObject Dim rootFolder As Folder.GetFolder(folderName) If firstTime = True Then folderCount = 0 End If txtDisplay. strSummary As String strStart = dirFiles.GetFolder(strStart) numFolders = displayFolder(strStart. " strSummary = strSummary & "Total size: " & Format(startFolder.Text & vbCrLf & strSummary Else txtDisplay. True) strSummary = numFolders & " Folders.SubFolders txtDisplay.Text = "" Set startFolder = fso.Text = txtDisplay. currentFolder As Folder.Text & rootFolder & vbCrLf folderCount = folderCount + 1 For Each currentFolder In rootFolder.Size.Text = "" End If Set startFolder = Nothing Set fso = Nothing End Sub Private Function displayFolder(ByVal folderName As String. "#. subFolder As Folder Static folderCount As Integer Set rootFolder = fso.Path.

Path End Sub Private Sub drvDrive_Change() On Error GoTo driveError retryDrive: dirList.Text End If End Sub Dim Dim Dim For Loading subdirectories into the TreeView control The following example lists all of the directories in the C Drive in a TreeView control.Attributes = attValue Next counter End Sub Private Sub dirList_Change() filList. When the "Select Files" CommandButton is clicked. attValue As Integer counter = 0 To filList.Value = 1 Then attValue = 2 End If f.Value = 1 Then attValue = 32 End If If chkAttributes(1).SelStart = 0 txtPattern.ListCount .Path & "\" & filList.Pattern = txtPattern.Path = drvDrive. "Drive Error") If response = vbRetry Then Resume retryDrive End If End Sub Private Sub txtPattern_GotFocus() txtPattern.Value = 1 Then attValue = 1 End If If chkAttributes(2).fso As New FileSystemObject f As File counter As Integer.Path = dirList.1 Set f = fso.Drive Exit Sub driveError: Dim response As Integer.GetFile(filList.description. description As Integer description = vbExclamation + vbRetryCancel response = MsgBox(Err. the nodes with a check in them are added to the Selection TextBox.List(counter)) attValue = 0 If chkAttributes(0). description. 8 .Text) End Sub Private Sub txtPattern_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 filList.SelLength = Len(txtPattern.

Text & x.Key & vbCrLf End If Next x End Sub Private Sub Form_Activate() Dim fso As New FileSystemObject. tvwNext.SubFolders addFolder subFolder.Checked Then txtSelection. "closed" For Each subFolder In currentFolder. rootFolder.Nodes.Name.Checkboxes = True Set startFolder = fso.Add strParentName.GetFolder("C:\") For Each subFolder In startFolder.Image = "closed" End Sub Private Sub tvwFileSystem_Expand(ByVal Node As MSComctlLib.IsRootFolder Then strParentName = rootFolder.ImageList = imlImages tvwFileSystem.Nodes If x.Add . subFolder As Folder tvwFileSystem. rootFolder. startFolder As Folder. rootFolder.Node) Node.SubFolders tvwFileSystem. "closed" End If End If For Each currentFolder In rootFolder. currentFolder.Image = "open" End Sub Private Sub addFolder(ByVal folderName As String) Dim fso As New FileSystemObject Dim rootFolder As Folder. closed" Else tvwFileSystem.Option Explicit Private Sub cmdSelect_Click() Dim x As Node txtSelection.Nodes. tvwChild.ParentFolder If Len(strParentName) > 3 Then tvwFileSystem.SubFolders addFolder CStr(subFolder) Next subFolder End Sub Private Sub tvwFileSystem_Collapse(ByVal Node As MSComctlLib.GetFolder(folderName) If Not rootFolder.Name.Nodes.Name. rootFolder. currentFolder As Folder.Add CStr(rootFolder).Text = "" For Each x In tvwFileSystem. subFolder As Folder Dim strParentName As String Set rootFolder = fso.Text = txtSelection. currentFolder.Path Next subFolder Next currentFolder End Sub RANDOM ACCESS FILES: 9 . tvwChild.Node) Node.

10 . Open filename For Random Access Read Write As #1 Len = recordLength The As clause specifies a file number that will be used as a handle to reference the file. Data may be inserted into the file without destroying any other data in the file. which may be thought of as a record. the default is read and write. Members of the record are accessed using the dot operator as in the following example. String variables are given a fixed length in order that the record is a fixed length. USER DEFINED TYPES: A user defined type is a collection of variables that create a new type. The FreeFile can be used to get the next free file number.accountNumber = 100 Debug. which is the case with sequential files.Print cr. Data may also be amended or deleted without having to rewrite the entire file. "write only" or "read and write". They are commonly used to define fixed length records that may be used in random access files.Net. If no mode is specified.accountNumber Note: Fixed length strings are not supported in VB. OPENING RANDOM ACCESS FILES: Random access files may be opened as "read only". The following is an example of a user defined type in Visual Basic. Dim cr As clientRecord cr.Visual Basic uses fixed length records in order to implement random access files. Private Type clientRecord accountNumber As Integer strSurname As String * 15 strForename As String * 15 balance As Currency End Type The variables declared within the type are members of the type.

FileTitle = "" ' Open the file for read and write Open strFilename For Random Access Read Write As #1 Len = 11 . The Get function takes as parameters the file handle. and Put is used to write a user defined record to a file. The following example gets record 8 from file handle 1 and places it in a user defined record.filename Loop While cdlOpen.Dim fileNum As Integer fileNum = FreeFile Open filename For Random As #fileNum Len = recordLength Reading and Writing to Random Access Files Get is used to read a record a record from a text file into a user defined record. Option Explicit Private Type clientRecord accountNumber As Integer strSurname As String * 15 strForename As String * 15 balance As Currency End Type Private Sub Form_Activate() Dim strFilename As String Dim recordLength As Long Dim cr As clientRecord recordLength = LenB(cr) On Error GoTo userCancelled cdlOpen. and the user defined type. If the file does not exist. Get #1. Put #1. userRecord The Put function takes as parameters the file handle.ShowOpen strFilename = cdlOpen. and the user defined record. the record number. 8. 100 blank records are written to the file. 4. The following example write the data stored in the user defined type to record 4 from file handle 1.CancelError = True ' Get a valid filename Do cdlOpen. userRecord RANDOM ACCESS FILE EXAMPLE The following example uses a user-defined type for a random access file. the record number.

Caption) > 1 Then updateRecord populateFields Val(lblAccountNumber.recordLength Get #1. vbInformation. "Exit Program") If response = vbNo Then Cancel = True Else updateRecord Close #1 End If End Sub Private Sub initialiseFile() Dim counter As Integer Dim blankRecord As clientRecord ' write 100 blank records to the file For counter = 1 To 100 blankRecord. vbQuestion + vbYesNo.1) Else MsgBox "At first record".Caption . 1.Caption + 1) Else MsgBox "At last record". "Random Access Files" End If End Sub Private Sub Form_Unload(Cancel As Integer) Dim response As Integer response = MsgBox("Are you sure".accountNumber = 0 Then initialiseFile End If populateFields 1 Exit Sub userCancelled: ' The user chose to cancel.Caption) < 100 Then updateRecord populateFields Val(lblAccountNumber. vbInformation. "Random Access Files" End If End Sub Private Sub cmdPrevious_Click() If Val(lblAccountNumber.accountNumber = counter Put #1. cr If cr. so end the program End End Sub Private Sub cmdFirst_Click() updateRecord populateFields 1 End Sub Private Sub cmdLast_Click() updateRecord populateFields 100 End Sub Private Sub cmdNext_Click() If Val(lblAccountNumber. blankRecord Next counter 12 . counter.

Val(lblAccountNumber. recNo.Text = cr.Text cr.SetFocus End Sub Private Sub updateRecord() Dim cr As clientRecord cr. cr End Sub Private Sub txtBalance_GotFocus() txtBalance.balance = Val(txtBalance.Text) Put #1.Text)) End Sub Private Sub txtForename_GotFocus() txtForename.strForename txtSurname.strForename = txtForename.MsgBox "File initialised".Text cr.Caption) cr.strSurname = txtSurname.strSurname txtBalance.Text = cr.SelLength = Len(Trim(txtForename.SelLength = Len(Trim(txtSurname.SelStart = 0 txtForename.SelLength = Len(Trim(txtBalance. "Random Access Files" End Sub Private Sub populateFields(ByVal recNo As Integer) Dim cr As clientRecord Get #1.Caption = cr.accountNumber txtForename.SelStart = 0 txtSurname.accountNumber = Val(lblAccountNumber.Text)) End Sub 13 . cr lblAccountNumber.SelStart = 0 txtBalance.Text = cr.balance txtForename. vbInformation.Caption).Text)) End Sub Private Sub txtSurname_GotFocus() txtSurname.