File System Object Dialouge Box Built in Functions of VB
File System Object Dialouge Box Built in Functions of VB
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.
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:
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.
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.
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.
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 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.
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.
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 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).
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 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.
LTrim(str)
RTrim(str)
UCase(str)
LCase(str)
Chr(charCode)
Asc(character)
Maths functions
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)
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).
"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"
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"