Data based systems Blog

B File-system Manipulation

Example Visual Basic Applications

n        Rename a directory of files

n        Replace a text string within a directory of files – without opening each file with an editor.

Help Topics

n        Using Sequential File Access

n        Filename property (Multimedia MCI control example)

n        Using the file system controls – drive, directory and file list boxes (Winseek.vbp example)

Using Sequential File Access

Sequential access works best when data is not divided into a series of records.  Because each number is stored as a character string in a sequential file, a four-digit number would require 4 bytes of storage instead of the 2 bytes it requires to store the same number as an integer.

Opening Files for Sequential Access

When you open a file for sequential access, you open it to perform one of the following operations:

  • Input characters from a file (Input)
  • Output characters to a file (Output)
  • Append characters to a file (Append)

To open a file for sequential access, use the following syntax for the Open statement:

Open pathname For [Input | Output | AppendAs filenumber [Len = buffersize]

See “Open Statement” in the Language Reference in Books Online.

When you open a sequential file for Input, the file must already exist; otherwise, an error occurs. When you try to open a nonexistent file for Output or Append, however, the Open statement creates the file first and then opens it.  The optional Len argument specifies the number of characters to buffer when copying data between the file and your program.  After opening a file for an Input, Output, or Append operation, you must close it, using the Close statement, before reopening it for another type of operation.

Editing Files Opened for Sequential Access

To edit a file …

1)      first read its contents to program variables, then

2)      change the variables, and finally,

3)      write the variables back to the file.

Reading Strings from Files

To retrieve the contents of a text file, open the file for sequential Input.  Then, use the Line Input #, Input( ), or Input # statement to copy the file into program variables.  Visual Basic provides statements and functions that will read and write sequential files one character at a time or one line at a time.

For example, the following code fragment reads a file line by line:

Dim LinesFromFile, NextLine As String

Do Until EOF(FileNum)

            Line Input #FileNum, NextLine

LinesFromFile = LinesFromFile + NextLine + Chr(13) + Chr(10)


Although Line Input # recognizes the end of a line when it comes to the carriage return–linefeed sequence, it does not include the carriage return–linefeed when it reads the line into the variable.  To retain the carriage return–linefeed, your code must add it e.g. + Chr(13) + Chr(10).

You can also use the Input # statement, which reads a list of numbers and/or string expressions written to the file.  For example, to read in a line from a mailing list file, you might use the following statement:

Input #FileNum, name, street, city, state, zip

You can also use the Input function to copy any number of characters from a file to a variable, provided the variable is large enough.  For example, the following code uses Input to copy an entire file at once to a variable:

LinesFromFile = Input(LOF(FileNum), FileNum)

Writing Strings to Files

To store the contents of variables in a sequential file, open it for sequential Output or Append and use the Print # statement.  For example, a text editor might use the following line of code to copy the contents of a text box into a file:

Print #FileNum, TheBox.Text

Visual Basic also supports the Write # statement, which writes a list of numbers and/or string expressions to a file. Write # automatically separates each expression with a comma and puts quotation marks around string expressions:

Dim AnyString As String, AnyNumber As Integer

AnyString = “AnyCharacters”

AnyNumber = 23445

Write #FileNum AnyString, AnyNumber

This code segment writes two expressions to the file specified by FileNum.  The first contains a string and the second contains the number 23445.  Therefore, Visual Basic writes the following characters (including all punctuation) to the file:


Note   If your data is record-oriented, random or binary access are more suitable than Write # and Input #, which are best suited to sequential access.

Related File Properties

Files Property

Returns a DataObjectFiles collection, containing a list of all filenames used by a DataObject object (such as the names of files that a user drags to or from the Windows File Explorer.)




object           An object expression that evaluates to a DataObject object.

index          An integer which is an index to an array of filenames.Filename property

FileName Property

Applies To CommonDialog Control (Open, Save As Dialogs), FileListBox Control

Returns or sets the path and filename of a selected file.  Not available at design time for the

FileListBox control.


object.FileName [=  pathname]

object           An object expression that evaluates to an object in the Applies To list.

pathname     A string expression that specifies the path and filename.


When you create the control at run time, the FileName property is set to a zero-length string (“”), meaning no file is currently selected.

In the CommonDialog control, you can set the FileName property before opening a dialog box to set an initial filename.

Reading this property returns the currently selected filename from the list. The path is retrieved separately, using the Path property.  The value is functionally equivalent to List(ListIndex). If no file is selected, FileName returns a zero-length string.

When setting this property:

  • Including a drive, path, or pattern in the string changes the settings of the Drive, Path, and Pattern properties accordingly.
  • Including the name of an existing file (without wildcard characters) in the string selects the file.
  • Changing the value of this property may also cause one or more of these events: PathChange (if you change the path), PatternChange (if you change the pattern), or DblClick (if you assign an existing filename).
  • This property setting can be a qualified network path and filename using the following syntax:      \\servername\sharename\pathname

FileNames Property

Returns the current path name(s) in which the component will be stored.



object           An object expression that evaluates to an object in the Applies To list.

index          A long integer, specifying the filename location in the returned indexed string.


The path name returned will always be provided as an absolute path (for example, “c:\projects\myproject.vbp”), even if it is shown as a relative path in Visual Basic (such as “..\projects”).

The number of entries in the indexed string is determined by the FileCount property setting.

File system controls – drive, directory and file list boxes

Many of the code examples are taken from the WinSeek sample application in the Visual Basic directory (\VB\Samples\Misc\Filectls\Winseek.vbp).  WinSeek.vbp browses drives and directories and displays any category of files e.g. files with a specified extension.

Synchronizing the File System Control Displays

The user selects a drive in the Drive1 list box …

  1. When a Drive1_Change event is generated, the Drive1 display is updated to reflect the new drive.  Code in the Drive1_Change event procedure assigns the new selection (the Drive1.Drive property) to the Path property of the Dir1 list box:

Private Sub Drive1_Change ()

            Dir1.Path = Drive1.Drive

End Sub

  1. The assignment to the Path property generates a Dir1_Change event and updates the  Dir1 display to reflect the current directory of the new drive.  Code in the Dir1_Change event procedure assigns the new path (the Dir1.Path property) to the File1.Path property of the File1 list box:

Private Sub Dir1_Change ()

            File1.Path = Dir1.Path

End Sub

  1. The assignment to the File1.Path property causes the File1 list box display to reflect the Dir1 path specification.  The code in “File-System Controls Scenario: A File Seeker Application” illustrates the synchronization of controls described here.

String Functions

These functions have an ANSI/DBCS version and a binary version and/or Unicode version, as shown in the following table.  Use the appropriate functions, depending on the purpose of string manipulation.

The “B” versions of the functions in the following table are intended especially for use with strings of binary data.  The “W” versions are intended for use with Unicode strings.

Function Description
Asc Returns the ANSI or DBCS character code for the first character of a string.
AscB Returns the value of the first byte in the given string containing binary data.
AscW Returns the Unicode character code for the first character of a string.
Chr Returns a string containing a specific ANSI or DBCS character code.
ChrB Returns a binary string containing a specific byte.
ChrW Returns a string containing a specific Unicode character code.
Input Returns a specified number of ANSI or DBCS characters from a file.
InputB Returns a specified number of bytes from a file.
InStr Returns the first occurrence of one string within another.
InStrB Returns the first occurrence of a byte in a binary string.
Left, Right Returns a specified number of characters from the right or left sides of a string.
LeftB, RightB Returns a specified number of bytes from the left or right side of a binary string.
Len Returns the length of the string in number of characters.
LenB Returns the length of the string in number of bytes.
Mid Returns a specified number of characters from a string.
MidB Returns the specified number of bytes from a binary string.
StrConv For are converting uppercase to lowercase and vice versa.

Use the character-based functions when you can because these functions can properly handle ANSI strings, DBCS strings and Unicode strings.  The functions without a “B” or “W” in this table correctly handle DBCS and ANSI.  When you store the characters to a String variable or get the characters from a String variable, Visual Basic automatically converts between Unicode and ANSI characters.


When you handle the binary data, use the Byte array instead of the String variable and the byte-based string manipulation functions.  To handle strings of binary data, you can map the characters in a string to a Byte array by using the following code:

Dim MyByteString() As Byte

‘ Map the string to a Byte array.

MyByteString = “ABC”

‘ Display the binary data.

For i = LBound(MyByteString) to UBound(MyByteString)

      Print Right(” ” + Hex(MyByteString(i)),2) + ” ,”;



DBCS = Double-byte Character Set

The double-byte character set (DBCS) was created to handle East Asian languages that use ideographic characters, which require more than the 256 characters supported by ANSI. Characters in DBCS are addressed using a 16-bit notation, using 2 bytes.  With 16-bit notation you can represent 65,536 characters, although far fewer characters are defined for the East Asian languages.

DBCS String Conversion

Visual Basic provides several string conversion functions that are useful for DBCS characters: StrConv, UCase, and LCase.

Comparing Strings

Comparing Strings with the Option Compare Statement

When using the Option Compare statement, you must specify a string comparison method: either Binary or Text for a given module.  If you specify Binary, comparisons are done according to a sort order derived from the internal binary representations of the characters.  If you specify Text, comparisons are done according to the case-insensitive textual sort order determined by the user’s system locale.  The default text comparison method is Binary.

Comparing Strings with the Like Operator

The Like operator can compare two strings.  You can also use its pattern-matching capabilities.

Comparing Strings with the StrComp Function

The StrComp function returns a value that tells you whether one string is less than, equal to or greater than another string.  The return value depends on the string comparison method (Binary or Text) that you defined with the Option Compare statement.

Leave a Reply

Your email address will not be published. Required fields are marked *