Sei sulla pagina 1di 10

VB6's File System Objects

File System Objects (FSO) completely recast Visual Basics fundamental powers over disk storage in an object-oriented mold. It makes file access and management considerably easier, even though it isnt quite complete.

Text File Access with FSO


The top dog in the FSO hierarchy is the FileSystemObject class. To read or write a text file, you must first create an instance of this class:

Dim myFSO Set myFSO = _ CreateObject("Scripting.FileSystemObject")

The following alternate syntax accomplishes the same thing:

Dim myFSO As New Scripting.FileSystemObject

The Scripting qualifier identifies the library in which the FileSystemObject class is defined. To use the class, you do not need to select the Microsoft Scripting Runtime library in the Visual Basic References dialog box, but doing so will give you access to the classes, methods, and properties in the Object Browser. (If you are not familiar with the Object Browser, you owe it to yourself to find out; it is a great source of information about classes.)

After creating an instance of the FileSystemObject class, the next step is to create a TextStream object. A TextStreamobject is nothing more than a regular text file enclosed in an FSO wrapper. The FileSystemObject has two methods for creatingTextStream objects:

y y

CreateTextFile creates a new text file. If a file of the same name already exists, it is overwritten. OpenTextFile opens a text file for reading and/or writing. If the file already exists, new data is appended to existing data.

The syntax for these methods is similar. In these examples, assume that myFSO is a FileSystemObject and that it has been declared as a type Variant or Object. The first line of code creates a new file, and the second line opens an existing file:

Set ts = myFSO.CreateTextFile(filename[, overwrite[, unicode]]) Set ts = myFSO.OpenTextFile(filename[, iomode[, create[,_ format]]])

Filename is a string expression specifying the name (including path information) of the file. The overwrite argument is eitherTrue or False, indicating whether an existing file will be overwritten. If this argument is omitted, the default is False. Ifoverwrite is False and filename already exists, an error occurs. You can trap this error to permit the user to verify file overwrites. Set unicode to True to create a Unicode file, or False (the default) for an ASCII file. Set iomode to the constantsForReading or ForAppending to read the file or write data to the end of the file, respectively. A file opened using ForReadingcannot be written to. Set create to True or False to specify whether a new file will be created if the file named in the filenameargument does not exist. The

default is False. The format argument is a tristate argument (that is, one that can take on one of three possible values) that determines the format of the file:

y y

TriStateTrue opens the file as Unicode. TriStateFalse (the default) opens the file as ASCII.

TristateUseDefault uses the system default format setting.

The iomode and format arguments are the same as described above for the CreateTextFile and OpenTextFile methods. Heres the code necessary to create a TextStream object associated with an existing file DEMO.TXT for reading, using theOpenAsTextStream method:

Dim myFSO, f, ts Set myFSO = CreateObject("Scripting.FileSystemObject") Set f = myFSO.GetFile("demo.txt") Set ts = f.OpenAsTextStream(ForWriting, _ TristateUseDefault)

Table 1. Properties of the TextStream object. Property AtEndOfLine AtEndOfStream Column Line Description True if the file pointer is at the end of a line; False otherwise. This property applies only to TextStreamfiles that are open for reading; otherwise, an error occurs. True if the file pointer is at the end of the file; False otherwise. This property applies only to TextStreamfiles that are open for reading; otherwise, an error occurs. Returns the column number of the file pointer. The first character on a line is at column 1. Returns the current line number.

The TextStream object has a number of methods to read and write data. These methods are described in Table 2.

Table 2. Methods of the TextStream object. Property Close Read(n) ReadAll ReadLine Skip(n) SkipLine Write(s) Description Closes the file associated with the TextStream object. Always execute the Close method when you are done reading/writing the file. Reads the next n characters from the file and returns the resulting string. Reads the entire file and returns the resulting string. Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string. Skips ahead (moves the file pointer) by n characters. Skips to the beginning of the next line. Writes the string s to the file. No extra or newline characters are added. Writes the string s to the file followed by a newline character.

WriteBlankLines(n) Writes n blank lines to the file. WriteLine(s)

Be aware that certain of these methods are applicable only when the file has been opened for reading or writing. If you try to use a method that is inappropriate for the files mode, an error will occur.

File Management with FSO


As with file access, file management with FSO is based upon the FileSystemObject class. Ive already shown you how to create an instance of this class. Once you have done this, you can use its properties and methods to perform the file manipulation tasks required by your program.

As mentioned earlier, the FileSystemObject is the top object in the FSO hierarchy. As such, it provides access to all of the systems drives (both local and network), folders, and files. There are several other objects in the hierarchy, and you can see that they correspond to the way in which disk drives are organized:

y y y

Drive object, which corresponds to a single disk drive on the system. Folder object, which corresponds to a single folder on a drive. File object, which corresponds to a single file in a folder.

The following is a brief overview of how the FSO system works. The FileSystemObject has a Drives collection that contains one Drive object for each local and network drive. You can query a Drive objects properties to obtain information about the drive, such as its type and the amount of free space. Each Drive object contains a single Folder object representing the drives top-level folder, or root. Each Folder object contains a Folders collection and a Files collection. The Folders collection contains a Folder object for each subfolder within the folder, and the Files collection contains a File object for each file in the folder.

The Drives, Folders, and Files collections are like any other Visual Basic collection, and they are used the same way. (I cant explain collections here, but its a good idea for you to understand them because they are used a lot in Visual Basics objects.)

Each Drive object has a set of properties (listed in Table 3) that provides information about the physical drive. Except as noted, these properties are all read-only.

The File Object


Now lets turn our attention to the final member of the FSO team, the File object. In the FSO model, each file on a disk is represented by a File object. There are two ways to create a File object. If you know the name and path of the file, you can use the FileSystemObjects GetFile method. Assuming that fs is an instance of the FileSystemObject class:

Dim f Set f = fs.GetFile(filespec)

The argument filespec contains the filename, including a relative or absolute path. An error occurs if the file called out infilespec does not exist. Note that executing GetFile does not open the file, it simply returns a File object linked to the file.

Another way to obtain a File object is from a Folder objects Files collection. As you learned earlier, you can create a Folderobject for any subfolder on a disk, and the Folder object contains

a Files collection containing one File object for each file in the folder. You can write code to iterate through the collection, looking for one or more files that meet a specified criterion. For example, the following code creates an array of File objects containing all the DLL files in the applications current path:

Dim fs, f, f1, filelist() Dim i As Integer, j As Integer i = 0 ReDim filelist(0) Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(App.Path) For Each f1 In f.Files If LCase(Right(f1.Name, 3)) = "dll" Then i = i + 1 ReDim Preserve filelist(i) Set filelist(i) = f1 End If Next

Once you create a File object, you have access to all the properties of the file. You can also use the objects methods for certain types of file manipulation. The methods and properties are explained in Tables 5 and 6.

Table 5. The File objects methods. Method Description

Copy dest [, overwrite] Copies the file to dest. An existing file is overwritten only if overwrite is True (the default). Move dest Delete [force] OpenAsTextStream Moves the file to dest. Deletes the files. Read-only files are deleted only if force is True. The default is False. Opens the file and returns a TextStream object.

VB6's Common Dialog control


Many Windows programs have things in common, such as dialog boxes for opening files, selecting colors, or starting a print job. When you need this kind of functionality in your VB6 program, you may want to turn to the Common Dialog control instead of creating your own dialog box. To use this control, you must select Microsoft Common Dialog Control 6.0 on the Controls tab in the Components window (select Project | Components from the menu). Then, the control icon will appear in your toolbox and you can add it as a form like any other control. At run time, it's invisible until you need it. The Common Dialog control is very flexiblein fact, it's five dialog boxes in one. You choose the dialog box you need by the method you call on the control. Here are brief descriptions of the dialog boxes: ShowOpen: Shows a File Open dialog box. ShowSave: Shows a File Save dialog box. ShowColor: Shows a Select Color dialog box.

y y y

y y

ShowFont: Shows a Font Selection dialog box. ShowPrinter: Shows a Print/Print Options dialog box. The control has a range of properties, many of which are relevant only for a specific type of dialog box. For example, when using the ShowOpen method, you can set properties to specify the starting folder and the types of files that are shown. Likewise, the Color dialog box has a property that returns the color the user selects. A nice feature is that each dialog box automatically provides context-sensitive help on its elements. Here's an example of using the File Open dialog box. Assume the control is named cdlg. The dialog box will initially show only *.txt files in the c:\temp folder: cdlg.Filter = "Text (*.txt) | *.txt" cdlg.InitDir = "c:\temp" cdlg.ShowOpen if cdlg.FileName = "" Then ' User canceled. Else ' The FileName property contains the selected file name. End If The Common Dialog control can save a lot of programming time, as well as provide a standard Windows look to certain parts of your program.

Built-in Functions
Visual Basic .NET has many built-in functions for manipulating text and carrying out mathematical operations, as well as the the ability to format data in both standard and user-derfined styles. We start by looking at two functions that are both frequently used and at the same time relatively easy to get to grips with the MsgBox() function and the InputBox() function. We will then look at some of the more commonly-used string-handling and math functions, and the ways in which numerical, date and time values can be represented.

The MsgBox() function


The MsgBox() function displays a message in a pop-up message box (no surprises there!). The user is expected to respond by clicking on a button in order to be able to continue. The format of the statement used to invoke a message box is as follows:

returnVal = MsgBox(prompt, styleVal, title)

The prompt parameter is a string value (either a string literal or a string variable) that supplies the message to be displayed. The styleVal parameter is either an integer style value from 0 to 5 or a named constant (that can be used instead of

the corresponding integer value) that determines what command buttons will appear on the message box. The title parameter is another string literal or string variable that supplies the title for the message box. The styles available are listed in the table below.

Message Box Styles Style value Named constant 0 1 2 3 4 5 vbOkOnly vbOkCancel Buttons displayed Ok Ok and Cancel

vbAbortRetryIgnore Abort, Retry and Ignore vbYesNoCancel vbYesNo vbRetryCancel Yes, No and Cancel Yes and No Retry and Cancel

The returnVal value returned by the MsgBox() function is an integer value that indicates which button the user has clicked in response to the message box being displayed. The possible return values together with the named constants that may be used in their stead, are listed in the table below.

Message Box Return Values Return value Named constant Buttons clicked 1 2 3 4 5 6 7 vbOk vbCancel vbAbort vbRetry vbIgnore vbYes vbNo Ok Cancel Abort Retry Ignore Yes No

The message box can be further embellished by the inclusion of an icon that will appear beside the message. In VB.NET, there are four icons available. The icon is included either by incrementing the style value by a fixed constant value, or by the inclusion of a second named constant (see table below).

Message Box Icons Value Named constant 16 vbCritical Icon

32

vbQuestion

48

vbExclamation

64

vbInformation

The following two program statements would produce exactly the same message box, and are essentially equivalent to one another:

MsgBox("This message is for info!", 64, "Info") MsgBox("This message is for info!", vbOKOnly + vbInformation, "Info")

The InputBox() function


The InputBox() function displays a pop-up input box into which the user can type a message. The user is expected to enter their message, then click on a button ("Cancel" or "OK") in order to continue. The format of the statement used to invoke an input box is as follows:

returnString = InputBox(prompt, title, defaultText, xpos, ypos)

The returnString returned by the InputBox() function is the text entered by the user. The prompt parameter is a text string (either a string literal or a string variable) that prompts the user to enter some information. The title parameter is another string literal or string variable that supplies the title for the input box. The defaultText parameter can be used to enter default content in the input box (although it would probably be left blank in most cases). The xpos and ypos parameters specify the x and y coordinates for the input box on screen.

String functions

String Functions Function Mid(str, pos, n) Description Returns n characters from the text string referred to by str, starting at character position pos. Returns the n left-most characters from the text string referred to by str. Returns the n right-most characters from the text string referred to by str. Removes the white space (if any) at either end of the text string referred to by str, and returns the result. Removes the white space (if any) at the left-hand end of the text string referred to by str, and returns the result. Removes the white space (if any) at the right-hand end of the text string referred to by str, and returns the result. Looks for an occurrence of the substring str2 within the string str1, starting at character position n. If successful, the function returns the character position at which the substring is found (or zero if the substring cannot be found). Converts the string referred to by str to all upper-case characters, and returns the result. Converts the string referred to by str to all lower-case characters, and returns the result. Returns the ASCII character corresponding to the 8-bit character code charCode (note some characters are non-printing characters, and will not be visible on screen). Returns the 8-bit ASCII character code corresponding to character.

Microsoft.VisualBasic.left(str, n) Microsoft.VisualBasic.right(str, n) Trim(str)

LTrim(str)

RTrim(str)

InStr(n, str1, str2)

UCase(str)

LCase(str)

Chr(charCode)

Asc(character)

Maths functions

Maths Functions Function Description

Math.Sqrt(n) Returns the square root of a number, n. Math.Abs(n) Math.Exp(n) Returns the absolute value of a number, n. Returns the exponential value of a number, n i.e. e . Note: e = 2.71828182 Returns the integer part of a floating point number, n. Returns the integer part of a floating point number, n, for positive numbers, or the next smallest integer value for negative numbers.
n

Fix(n) Int(n)

Math.Log(n) Rnd() Round(n,m)

Returns the natural logarithm of a number, n. Returns a randomly generated value between 0 and 1. Rounds a number, n, up (or down) to m decimal places.

Formatting numbers
The Format() function allows you to specify precisely how numeric values are displayed. The function is used as follows:

Format(n, "styleArg")

The first argument (n) is the number to be formatted. The value selected for the second argument ("styleArg") will determine how the number is displayed. The possible values are described in the table below (note that a user-defined value for "styleArg" can also be used).

Format() Number Style Arguments Style Argument Description

"General Number" Displays n with no separator between thousands. "Fixed" Displays n with no separator between thousands, and rounds it up (or down) to two decimal places. Displays n with separators between thousands, and rounds it up (or down) to two decimal places. Displays n prefixed by a "" sign (if the locale is set to United Kingdom), with separators between thousands, and rounds it up (or down) to two decimal places. Displays n as a percentage, rounds it up (or down) to two decimal places, and adds a "%" symbol.

"Standard"

"Currency"

"Percent"

Formatting the date and time


The Format() function can also be used to specify how date and time values are displayed. The function is used as follows:

Format(Date, "styleArg")

The first argument (Date) is the date to be formatted (note that if you are using the current date, the Now function can be used as the argument. The value selected for the second argument ("styleArg") will determine how the date value is displayed. The possible values are described in the table below (note that a user-defined value for "styleArg" can also be used).

Format() Date Style Arguments Style Argument Description "General Date" Displays the date and time in the format: dd/mm/yyyy hh:mm:ss Displays the date in the format: 06 October 2009 Displays the date in the format: dd/mm/yyyy Displays the time in the format: hh:mm:ss Displays the time in the format: hh:mm

"Long Date"

"Short Date"

"Long Time"

"Short Time"

Potrebbero piacerti anche