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 open an existing text file. Used to return the drive name. Used to return a specified drive. Used to return the name of the parent folder. Private Sub displayFileInfo(ByVal fileName As String) Dim fso As New FileSystemObject Dim fileSpec As File Dim strInfo As String Set fileSpec = fso.GetFile(fileName) strInfo = fileSpec. Used to copy an existing 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 determine whether a folder exists.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. Used to determine whether a file exists. Used to create a text file.Name & vbCrLf 2 . Used to move a folder. Used to create and return a string representing a file name. Used to return the full path name. Used to return a specified file. Used to create a folder. Used to return a specified folder. Used to delete a folder. Used to move a file. Used to delete a file.

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

overwrite an existing file or append text to the end of an existing file. fsoStream. "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. 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.WriteBlankLines 2 fsoStream." The FSO TextStream CreateTextFile Method 4 . 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.Else driveName = drv. The Write method is used to write a string. ForReading or ForWriting.Write "Hello" fsoStream.ShareName driveName = drv. WRITING TEXT FILES When writing to a file.FreeSpace If drv.WriteLine "First line in the text file. The CreateTextFile method is used to create a text file and return a reference to a TextStream object. vbInformation. you can either create a new file.

The default value is True. True) ' Write to the file fsoStream.txt". The ReadAll method reads the whole text file." fsoStream.WriteLine "Line after two blank lines. open the TextStream using the ForAppending parameter.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.WriteLine "Appending line to the text file" fsoStream.GetFile("c:\junk\junk." fsoStream.WriteLine "First line in the text file. Dim fso As New FileSystemObject Dim f As File Dim fsoStream As TextStream Set f = fso. Dim fso As New FileSystemObject Dim fsoStream As TextStream ' Create a text file. This is not advisable for large files as it's a waste of memory. 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.CreateTextFile("c:\junk\junk. Text written to the file is appended to the end. and return a reference to a TextStream Set fsoStream = fso. 5 .Close Set fsoStream = Nothing Set fso = Nothing APPENDING TO THE END OF A TEXTSTREAM To append to a file. The Read. ReadAll and ReadLine methods are used to read from the text file.OpenAsTextStream(ForAppending) ' Append lines to the file fsoStream. The Read method takes as a parameter the number of characters to be read.The following example creates a text file using the CreateTextFile method.txt") Set fsoStream = f.WriteBlankLines 2 fsoStream.

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

Option Explicit Private Sub cmdAttributes_Click() 7 .Text & currentFolder & vbCrLf folderCount = folderCount + 1 For Each subFolder In currentFolder.Text = txtDisplay. ByVal firstTime As Boolean) As Integer Dim fso As New FileSystemObject Dim rootFolder As Folder.Path.##0") txtDisplay.Text = txtDisplay.Text = txtDisplay.Text & rootFolder & vbCrLf folderCount = folderCount + 1 For Each currentFolder In rootFolder.SubFolders txtDisplay. " strSummary = strSummary & "Total size: " & Format(startFolder.GetFolder(strStart) numFolders = displayFolder(strStart. currentFolder As Folder. strSummary As String strStart = dirFiles. True) strSummary = numFolders & " Folders. subFolder As Folder Static folderCount As Integer Set rootFolder = fso.Size.Text = "" Set startFolder = fso.SubFolders folderCount = folderCount + displayFolder(subFolder. "#. 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.GetFolder(folderName) If firstTime = True Then folderCount = 0 End If txtDisplay.Text & vbCrLf & strSummary Else txtDisplay.Path ' Avoid root directories as it's likely to run out of memory If Len(dirFiles.Text = "" End If Set startFolder = Nothing Set fso = Nothing End Sub Private Function displayFolder(ByVal folderName As String.Path) > 3 Then txtDisplay.Dim numFolders As Integer Dim strStart As String.

description.Value = 1 Then attValue = 32 End If If chkAttributes(1).GetFile(filList.Attributes = attValue Next counter End Sub Private Sub dirList_Change() filList.ListCount .Path = drvDrive.SelLength = Len(txtPattern.SelStart = 0 txtPattern. description.1 Set f = fso. attValue As Integer counter = 0 To filList.Value = 1 Then attValue = 1 End If If chkAttributes(2).List(counter)) attValue = 0 If chkAttributes(0). "Drive Error") If response = vbRetry Then Resume retryDrive End If End Sub Private Sub txtPattern_GotFocus() txtPattern. When the "Select Files" CommandButton is clicked.Path & "\" & filList. the nodes with a check in them are added to the Selection TextBox.Path End Sub Private Sub drvDrive_Change() On Error GoTo driveError retryDrive: dirList. 8 .Value = 1 Then attValue = 2 End If f.Drive Exit Sub driveError: Dim response As Integer.Pattern = txtPattern. description As Integer description = vbExclamation + vbRetryCancel response = MsgBox(Err.Text) End Sub Private Sub txtPattern_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 filList.Path = dirList.fso As New FileSystemObject f As File counter As Integer.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.

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

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. 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.Net. If no mode is specified. Data may be inserted into the file without destroying any other data in the file. The following is an example of a user defined type in Visual Basic. They are commonly used to define fixed length records that may be used in random access files. the default is read and write.Print cr.accountNumber Note: Fixed length strings are not supported in VB. Data may also be amended or deleted without having to rewrite the entire file.Visual Basic uses fixed length records in order to implement random access files. "write only" or "read and write". which may be thought of as a record.accountNumber = 100 Debug. The FreeFile can be used to get the next free file number. 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. which is the case with sequential files. OPENING RANDOM ACCESS FILES: Random access files may be opened as "read only". 10 . Dim cr As clientRecord cr. Members of the record are accessed using the dot operator as in the following example.

filename Loop While cdlOpen. and Put is used to write a user defined record to a file. 4. 100 blank records are written to the file. The Get function takes as parameters the file handle. the record number. Get #1.ShowOpen strFilename = cdlOpen. The following example write the data stored in the user defined type to record 4 from file handle 1. the record number.FileTitle = "" ' Open the file for read and write Open strFilename For Random Access Read Write As #1 Len = 11 . 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.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.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. 8. If the file does not exist. Put #1. and the user defined type. The following example gets record 8 from file handle 1 and places it in a user defined record. and the user defined record. userRecord The Put function takes as parameters the file handle.

"Random Access Files" End If End Sub Private Sub Form_Unload(Cancel As Integer) Dim response As Integer response = MsgBox("Are you sure".Caption + 1) Else MsgBox "At last record".1) Else MsgBox "At first record".Caption) < 100 Then updateRecord populateFields Val(lblAccountNumber. blankRecord Next counter 12 .Caption) > 1 Then updateRecord populateFields Val(lblAccountNumber.accountNumber = 0 Then initialiseFile End If populateFields 1 Exit Sub userCancelled: ' The user chose to cancel. 1. cr If cr.accountNumber = counter Put #1.recordLength Get #1. vbInformation. vbQuestion + vbYesNo. 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. "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. vbInformation.Caption . counter. "Random Access Files" End If End Sub Private Sub cmdPrevious_Click() If Val(lblAccountNumber.

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