File Class VB.NET

Namespace
System.IO

Createable
No

Description
A File object represents a file. The members of the File class are listed in Public Static Methods. The Microsoft.VisualBasic.FileSystem class has members that duplicate much of the functionality of the File class. One significant omission from the FileSystem class is that there is no Exists method. Consequently, the File.Exists method is documented in its own entry. All of the methods of the File class are shared. Consequently, you don't need to instantiate a File object to access File class methods; you can simply reference the File class itself.

Public Static Methods
AppendText
Copy
Create
CreateText
Delete
Exists
GetAttributes
GetCreationTime
GetLastAccessTime
GetLastWriteTime
Move
Open
OpenRead
OpenText
OpenWrite
SetAttributes
SetCreationTime
SetLastAccessTime
SetLastWriteTime

File.Exists Method

Class
System.IO.File

Syntax
File.Exists(path)

path Use: Required Data Type: String

The file path

Return Value
A Boolean indicating whether the file exists

Description
Indicates whether a file exists

Rules at a Glance

  • path is a fully qualified filename or a relative path (which is interpreted as starting in the current directory).
  • The Exists method returns True only if the specified file exists; otherwise, it returns False. Note that Exists returns False if path describes a directory instead of a folder.

Programming Tips and Gotchas
Since the File class is shared, you don't have to instantiate any objects before calling the File.Exists method.

FileAttr Function

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileAttr(filenumber)

filenumber
Use: Required
Data Type: Integer

Any valid file number

Return Value
An OpenMode constant, as shown in the following table:

TABLE

TABLE

Description
Returns the file-access mode for a file opened using the FileOpen procedure

VB .NET/VB 6 Differences
In VB 6, FileAttr includes a superfluous returntype parameter that must be set to 1 or an error results. In VB .NET, the parameter has been eliminated.

FileClose Procedure

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileClose([filenumber][, filenumber][,...])

filenumber
Use: Optional Data Type: Integer

The file number (or numbers) of an open file (or files), opened using the FileOpen procedure

Description
Closes one or more files opened with the FileOpen procedure

Rules at a Glance

  • If filenumber is omitted, all open files are closed.
  • If the file you are closing was opened for Output or Append, the remaining data in the I/O buffer is written to the file. The memory buffer is then reclaimed.
  • When the FileClose procedure is executed, the file number used is freed for further use.
  • filenumber can either be a literal number, a numeric constant, or a numeric variable.

Programming Tips and Gotchas

  • With the FileClose procedure, you can close more than one file at once by specifying the file numbers as a comma-delimited list, as shown here: FileClose(1, 3, 4)
  • The FileClose procedure does not check first to see if there is a file associated with the given file number. Therefore, no error occurs if you use the FileClose procedure with a nonexistent file number. The drawback to this is that you may inadvertently think you have closed a file, when in fact you haven't.

VB .NET/VB 6 Differences

FileClose is new to VB .NET. It replaces the Close statement in VB 6.

FileCopy Procedure

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileCopy(source, destination)

source Use: Required Data Type: String

The name of the source file to be copied

destination Use: Required Data Type: String

The name and location of the file when copied

Return Value
None

Description
Copies a file

Rules at a Glance

  • The source and destination arguments may contain a drive name and a folder name, but they must always contain the filename.
  • You cannot copy a file that is currently open.

Programming Tips and Gotchas

  • If you don't specify a drive or folder in either the source or destination, the file is assumed to be in the current drive or folder.
  • Unlike copying a file from one folder to another from outside VB, when using the FileCopy procedure, it is not sufficient to simply enter a path for destination. You must supply a filename, even if it's the same as the source; otherwise, runtime error 75, "Path/File access error," results.
  • FileCopy is a procedure and not a function; there is no return value. You therefore have to assume that, if there are no errors generated from calling the FileCopy procedure, the file has been successfully copied. So be sure to wrap FileCopy in robust error handling.
  • Be aware that if the destination file already exists, it will be overwritten without warning.
  • A number of functions allow you to use the copy operation to rename a file. (Typically, this is done by specifying the same path in the destination as in the source, along with a different filename.) The FileCopy procedure, however, does not work in this way.
  • For the copy operation to succeed, source must not be open by another application; if it is, runtime error 70, "Permission denied," is generated. If source has already been opened by the application, the copy operation will still succeed if the file is not locked (i.e., has been opened with the Shared keyword) or has been opened with a write lock only. If source has already been opened with either a read lock or a read-write lock, the FileCopy operation will generate runtime error 70, "Permission denied."
  • destination must not be open if the copy operation is to succeed. If it has been opened by another application, runtime error 70, "Permission denied," is generated. If it has already been opened by the application itself, runtime error 55, "File already open," is generated.

FileDateTime Function

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileDateTime(pathname)

pathname Use: Required Data Type: String

The filename, along with an optional drive and path

Return Value
A Date containing the date and time at which the specified file was created or last modified (whichever is later)

Description
Obtains the date and time at which a particular file was created or last modified (whichever is later)

Rules at a Glance
If you don't specify a drive or folder with pathname, the file is assumed to be in the current drive or
folder.

Programming Tips and Gotchas

  • Use the File.Exists method (in the System.IO namespace) to determine that the file exists before calling FileDateTime. If pathname does not exist, your application generates runtime error 53, "File not found."
  • If a file has not been modified, its creation date and last modified date will be identical. However, if the file has been modified since its creation, the FileDateTime function only returns the last modified date. To obtain the file's creation date, you will have to resort to using the Window's API. The GetFileTime API call returns not only the date last modified, but the file's creation date and last access date as well.
  • You can also use FileDateTime on hidden files.

FileGet, FileGetObject Procedures

Class

Microsoft.VisualBasic.FileSystem

Syntax
FileGet(FileNumber, Value, RecordNumber)
FileGetObject(FileNumber, Value, RecordNumber)

FileNumber Use: Required Data Type: Integer

Any valid file number

Value Use: required Data Type: Any (see the first two items in "Rules at a Glance")

Variable in which to place file contents

RecordNumber Use: Optional Data Type: Integer

The location at which reading begins

Description
Copies data from a file on disk into a variable

Rules at a Glance

  • For the FileGet procedure, the variable can have one of the following data types:
  • Array
    Boolean
    Byte
    Char
    Date
    Decimal
    Double
    Integer
    Long
    Short
    Single
    String

  • For the FileGetObject procedure, the variable must be of type Object.
  • For files opened in Random mode, RecordNumber refers to the record number in the file.
  • For files opened in Binary mode, RecordNumber refers to the byte number within the file.
  • The number of bytes read by the FileGet procedure is governed by the data type of Value.

The following is the number of bytes read by each data type:

TABLE

TABLE

  • Note that the number of bytes read by a String variable depends on the length of the string. Hence, a string must be initialized to the desired size before calling the FileGet procedure.
  • The position of the first record or byte within a file is always 1.
  • When a record or a number of bytes is read from a file using FileGet, the file pointer automatically moves to the record or byte following the one just read. You can therefore read all data sequentially from a Random or Binary file by omitting RecordNumber, as this snippet shows:
  • FileGet is most commonly used to read data from files written with the FilePut function.

Example
This example illustrates the use of the Char data type to read and output each byte of a file.

Programming Tips and Gotchas
With the increase in the power, flexibility, and ease of use of modern DBMSs, the use of external standalone data files has fallen dramatically, which means that statements such as FileGet and FileOpen are becoming much less important.

VB .NET/VB 6 Differences
The FileGet and FileGetObject procedures are new to VB .NET. They are replacements for the Get statement in VB 6, whose syntax is similar to that of FileGet.

FileLen Function

Class
Microsoft.VisualBasic.FileSystem
Syntax
FileLen(pathname)

pathname
Use: Required Data Type: String

The filename, along with its path and drive name (optionally)

Return Value
A Long containing the length of the specified file in bytes

Description
Specifies the length of a file on disk

Rules at a Glance
If you don't specify a drive or folder with pathname, the file is assumed to be in the current drive or folder.

Programming Tips and Gotchas

  • Use the File.Exists method in the System.IO namespace to determine that the file exists before calling FileLen. If the file does not exist, FileLen generates runtime error 53, "File not found."
  • Because FileLen returns the length of a file based on the file allocation table, the value returned by FileLen will reflect the size of the file before it was opened. In the case of open files, you should instead use the LOF function to determine the open file's current length.

FileOpen Procedure

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileOpen(filenumber, filename, mode, access, share, recordlength)

filenumber Use: Required Data Type: Integer

An available file number.

filename Use: Required Data Type: String

The name of the file to open, along with an optional path.

mode Use: Optional Data Type: OpenMode enum

The file-access mode. Options are: OpenMode.Append, OpenMode.Binary, OpenMode.Input, OpenMode.Output, or OpenMode.Random (the default value).

access Use: Optional Data Type: OpenAccess enum

Specifies the allowable operations by the current process. Options are: OpenAccess.Default, OpenAccess.Read, OpenAccess.ReadWrite (the default value), or OpenAccess.Write.

share Use: Optional Type: OpenShare enum

Specifies the allowable operations by other processes. Options are: OpenShare.Shared (the default value), OpenShare.LockRead, OpenShare.LockWrite, or OpenShare.LockreadWrite.

recordlength Use: Optional Data Type: Integer (at most, 32767)

The length of the record (for random access) or of the I/O buffer (for sequential access).

Description
Opens a disk file for reading and/or writing

Rules at a Glance

  • There are three modes of file access: sequential, binary, and random. The Input, Output, and Append access modes are sequential access modes. Sequential access is designed for text files consisting of individual Unicode characters (and control codes). Most of the filemanipulation functions (LineInput, Print, PrintLine, and so on) apply to files opened for sequential access. Random access is designed to be used with files that have a structure— more specifically, files that consist of records, each of which is made up of the same set of fields. For instance, a record might contain name, address, and social security number fields. The binary access mode is for binary access, where each byte in the file is accessible independently.
  • filename may include the directory or folder and drive; if these are omitted, the file is assumed to reside in the current working directory. If filename does include drive and path information, this may take the form of a path relative to the local system or a UNC path.
  • The default mode for opening a disk file (when mode is not specified) is OpenMode.Random.
  • If the specified file does not exist when opening in Input mode, an error occurs.
  • A new file is created if the specified file does not exist when opening in Append, Binary, Output, or Random mode.
  • access allows you to restrict the actions that can be taken against the file in the current process, by specifying Read, Write, or ReadWrite. The default is OpenAccess.ReadWrite.

The share argument allows you to restrict the operations performed on the open file by other processes, and accepts one of the following members of the OpenShare enumeration:

TABLE

OpenShare enumeration:

  • The recordlength argument is treated differently, depending upon the open mode, as the following table shows:

TABLE

TABLE

Example
The following example opens a random access data file, adds two records, and then retrieves the second record:

<vbFixedString(length)> attribute to insure that the Name field is a constant size.

Programming Tips and Gotchas

  • So avoid using the file number of an already open file and generating an error, use the FreeFile function to allocate the next available file number.
  • You can open an already opened file using a different file number in Binary, Input, and Random modes. However, you must close a file opened using Append or Output before you can open it with a different file number.

VB .NET/VB 6 Differences
The FileOpen procedure is new to VB .NET. It is a more or less direct replacement for the VB 6 Openstatement.

FilePut, FilePutObject Procedures

Class
Microsoft.VisualBasic.FileSystem

Syntax
FilePut(filenumber, value, [recordnumber])
FilePutObject(filenumber, value, [recordnumber])

filenumber Use: Required Data Type: Integer Any valid file number value Use: Required Data Type: Any (see the first item in "Rules at a Glance")

The name of the variable containing the data to be written to the file

recordnumber Use: Optional Data Type: Integer

Record number (for random access) or byte number (for binary access) at which to begin the write operation

Description
Writes data from a program variable to a disk file
Rules at a Glance

  • The value argument of the FilePut procedure can be any data type except Object. The value argument of the FilePutObject procedure must be of type Object.
  • If filenumber is opened in random access mode, recordnumber refers to the record number; if the file is opened in binary access mode, recordnumber refers to a byte number.
  • Both bytes and records in a file are numbered starting with 1.
  • If recordnumber is omitted, the next byte or record to be written will be placed at the position immediately after the position pointed to by the last FileGet or FilePut procedure, or by the last Seek function.
  • If you have opened the file in Random mode, it is important to ensure that the record length specified in the recordNumber argument of the FileOpen procedure matches the actual length of the data being written. If the length of the data being written is less than that specified by the recordNumber argument, the space up to the end of the record will be padded with the current contents of the file buffer—whatever that may be. If, on the other hand, the actual data length is more than that specified, an error occurs.
  • The FilePut procedure cannot be used to write objects to disk. The FilePutObject procedure is used for this purpose.
  • If you open the file in Binary mode, the RecordNumber argument has no effect. When you use FilePut to write data to the disk, the data is written contiguously, and no padding is placed between records.

Example
The following code writes the letters A-Z to a file:

Programming Tips and Gotchas

  • Because of the structured format of data written with the FilePut procedure, it is customary to read the data back from the file using the FileGet procedure.
  • The FilePutObject procedure can be used to write data of type Object whose subtype is one of the standard datatypes (Boolean, Byte, Char, etc.). It cannot be used to write object data defined by the Class...End Class construct (including classes residing in .NET libraries), nor can it be used to write data from COM objects to disk. The following is a rewritten version of the example code that uses FilePutObject:
  • If you use the FilePut procedure to write data, you can use the FileGet procedure to read it. Similarly, if you use the FilePutObject procedure, you should should the FileGetObject procedure.

VB .NET/VB 6 Differences
The FilePut and FilePutObject procedures are new to VB .NET. They are almost direct replacements for the VB 6 Put statement.

FileWidth Procedure

Class
Microsoft.VisualBasic.FileSystem

Syntax
FileWidth(filenumber, recordwidth)

filenumber Use: Required Data Type: Integer

Any valid file number

recordwidth Use: Required Data Type: Numeric

A number between 0 and 255

Description
Specifies a virtual file width when working with files opened with the FileOpen function

Rules at a Glance

  • recordwidth defines the number of characters that can be placed on a single output line.
  • The default recordwidth of 0 denotes that there is no limit to the number of characters that can be placed on a single output line.

VB .NET/VB 6 Differences
The FileWidth procedure is new to VB .NET.

Filter Function

Class

Microsoft.VisualBasic.Strings

Syntax
Filter(Source, Match[, Include[, Compare]])

Source
Use: Required
Data Type: String or Object

An array containing values to be filtered.

Match Use: Required Data Type: String

The substring of characters to find in the elements of the source array.

Include Use: Optional Data Type: Boolean

A Boolean (True or False) value. If True (the default value), Filter includes all matching values in the returned array; if False, Filter excludes all matching values (or, to put it another way, includes all nonmatching values).

Compare Use: Optional Type: CompareMethod enumeration

A constant whose value can be CompareMethod.Text or CompareMethod.Binary (the default).

Return Value
A 0-based String array of the elements filtered from Source

Description
The Filter function produces an array of matching values from an array of source values that eithermatch or do not match a given filter string.Put another way, individual elements are copied from a source array to a target array if they either
match (Include is True) or do not match (Include is False) a filter string.A match occurs for an array element if Match is a substring of the array element.

Rules at a Glance

  • The default Include value is True.
  • The default Compare value is CompareMethod.Binary.
  • CompareMethod.Binary is case sensitive; that is, Filter matches both character and case. In contrast, CompareMethod.Text is case insensitive, matching only character regardless of case.
  • If no matches are found, Filter returns an empty array.

Programming Tips and Gotchas

  • Although the Filter function is primarily a string function, you can also filter numeric values. To do this, specify a Source of type Object and populate this array with numeric values. Then assign the string representation of the numeric value you wish to filter on to the Match parameter. Note, though, that the returned string contains string representations of the filtered numbers. For example:

In this case, the resulting array contains five elements: 123, 139, 1, 12, and 11.

Example

Fix Function

Class
Microsoft.VisualBasic.Conversion

Syntax
Fix(number)

number Use: Required Data Type: Double or any numeric expression

A number whose integer portion is to be returned

Return Value
A number of the same data type as number whose value is the integer portion of number

Description
For nonnegative numbers, Fix returns the floor of the number (the largest integer less than or equal tonumber).
For negative numbers, Fix returns the ceiling of the number (the smallest integer greater than or equalto number).

Rules at a Glance

  • If number is Nothing, Fix returns Nothing.
  • The operation of Int and Fix are identical when dealing with positive numbers: numbers are rounded down to the next lowest whole number. For example, both Int(3.14) and Fix(3.14) return 3.
  • If number is negative, Fix removes its fractional part, thereby returning the next greater whole number. For example, Fix(-3.667) returns -3. This contrasts with Int, which returns the negative integer less than or equal to number (or -4, in the case of our example).
  • The function returns the same data type as was passed to it.

Example

Programming Tips and Gotchas
Fix does not round number to the nearest whole number; it simply removes the fractional part of number. Therefore, the integer returned by Fix will be the nearest whole number less than (or greater than, if the number is negative) the number passed to the function.

Floor Function

Class
System.Math

Syntax
Math.Floor(d)d Use: Required Data Type: Double

Return Value
Returns a Double containing the largest integer less than or equal to the argument d.

Description
Returns the largest integer less than or equal to the argument d.

Example
Math.Floor(12.9) ' Returns 12
Math.Floor(-12.1) ' Returns -13

Rules at a Glance

  • Because this function can only accept numeric values, you may want to check the value you pass using the IsNumeric function to prevent generating an error.
  • This is a Shared member, so it can be used without creating any objects.

VB .NET/VB 6 Differences
The Floor function is new to the .NET Framework.

FontDialog Class

Namespace
System.Windows.Forms

Createable
Yes

Description
Represents a common dialog box for selecting or saving a font.The FontDialog object has properties for setting the initial appearance and functionality of the dialog box, a property for returning the font selected by the user, as well as a method for showing the dialog box.

Selected FontDialog Members
The following provides a brief description of the more important members of the FontDialog class:

Color property
Sets or retrieves the color of the font. The return value is an instance of the Color structure. The Color structure has a number of members, among which are:

  • Over 140 named color properties, from Red, Green, and Blue, to PapayaWhip, MistyRose, and MediumSeagreen. These properties return a Color structure.
  • A Name property, which returns the name of the color or its ARGB value for custom colors. (The A component is the alpha component of the color, which determines the color's opacity.)
  • The R property, G property, and B property, which return a byte specifying the red, green, or blue color component of the RGB color value, respectively.
  • The IsKnownColor, IsNamedColor, and IsSystemColor properties, which give information about the color. Please see the documentation for more information on these properties.

Font property
Sets or retrieves the font chosen by the user. The return value is an instance of the Font class in the System.Drawing namespace. The Font class has a number of members, among which are:

Bold, Italic, Strikout, Underline properties
Boolean properties used to set or retrieve the corresponding attribute of the font.

FontFamily property
Returns a FontFamily object associated with the font. Use the Name property to get the name of the font family.

Name property
Returns the face name of the font as a String.

SizeInPoints
Returns the size of the font, in points, as a Single.

Style
Returns a FontStyle constant that contains information about the style of the font. The FontStyle constants are Bold, Italic, Regular, Strikeout, and Underline, and they can be combined using bitwise operations.

MaxSize, MinSize properties
These are properties of type Integer that specify the maximum and minimum sizes that can be entered into the Font dialog box.

Show... properties
The FontDialog has properties that specify the features of the dialog box. These include:

ShowApply
Indicates whether the dialog box has an Apply button. (The default is False.)

ShowColor
Indicates whether the dialog box shows the font color choice controls. (The default is False.)

ShowEffects
Indicates whether the dialog box shows the strikethrough and underline options. (The default is True.)

Example
The following code displays the Font dialog box and then displays the user's choice of font family:

VB .NET/VB 6 Differences
While the FontDialog class is implemented in the .NET Base Class Library, VB 6 offers the CommonDialog custom control. Although the two offer similar functionality, their public interfaces are
almost completely different.

For...Next Statement

Syntax

A variable that serves as the loop counter

initial_value

Use: Required Data Type: Any valid numeric expression

The starting value of counter for the first iteration of the loop

maximum_value

Use: Required Data Type: Any valid numeric expression

The value of counter during the last iteration of the loop

stepcounter

Use: Optional (Required if Step is used) Data Type: Any valid numeric expression

The amount by which counter is to be incremented or decremented on each iteration of theLoop

Description
Defines a loop that executes a given number of times, as determined by a loop counter. To use the For...Next loop, you must assign a numeric value to a counter variable. This counter is either incremented or decremented automatically with each iteration of the loop. In the For statement, you specify the value that is to be assigned to the counter initially and the maximum value the counter will reach for the block of code to be executed. The Next statement marks the end of the block of code that is to execute repeatedly, and it also serves as a kind of flag that indicates that the counter variable is to be modified.

Rules at a Glance

  • If maximum_value is greater than initial_value and no Step keyword is used or the step counter is positive, the For...Next loop is ignored and execution commences with the first line of code immediately following the Next statement.
  • If initial_value and maximum_value are equal and stepcounter is 1, the loop will execute once.
  • counter cannot be a Boolean variable or an array element.
  • counter is incremented by one with each iteration unless the Step keyword is used.
  • The For...Next loop can contain any number of Exit For statements. When the Exit For statement is executed, program execution commences with the first line of code immediately following the Next statement.
  • If the Step keyword is used, stepcounter specifies the amount counter is incremented (if stepcounter is positive) or decremented (if it is negative).

Example
The following example demonstrates the use of a For...Next statement to iterate through the itemsin a combo box until an item in the combo box list matches a particular value entered in a text box:

The following example demonstrates how to iterate from the end to the start of an array of values:

For i = UBound(sArray) to LBound(sArray) Step - 1 Debug.WriteLine(sArray(i)) Next i

The following example demonstrates how to select only every other value from an array of value

For i = LBound(sArray) to UBound(sArray) Step 2 Debug.WriteLine(sArray(i)) Next i

Programming Tips and Gotchas

  • You can also nest For...Next loops, as shown here:
  • Although the counter following the Next keyword is optional, you will find your code is much easier to read if you use it, especially when nesting For...Next loops.
  • You should avoid changing the value of counter in the code within the loop. Not only can this lead to unexpected results; it makes for code that's incredibly difficult to read and to understand.
  • Once the loop has finished executing, the value of counter is officially undefined. That is, you should not make any assumptions about its value outside of the For...Next loop, and you should not use it unless you first reinitialize it.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics