Title: Working with the Windows File System and Essential Data Structures
1Chapter 5
- Working with the Windows File System and
Essential Data Structures
2Objectives (1)
- Understand the members of the System.IO namespace
- Understand the organization of the Windows file
system and how to manage directories and files - Configure the OpenFileDialog and SaveFileDialog
controls as a means for the user to select files
to open and save - Read and write sequential files using the
StreamReader and StreamWriter classes
3Objectives (2)
- Understand the basics of collections and work
with enumerators - Create and manage lists of data with the
ArrayList class - Create and manage sorted lists of data with the
SortedList class - Create first-in first-out lists, called queues
- Understand last-in first-out lists, called stacks
- Read and write random files
4Introduction to the System.IO Namespace
- The System.IO namespace supplies classes to
manage directories and files, and to read and
write files - System.IO.Directory class has methods to create,
move, rename, and delete directories - System.IO.File class works with files
- System.IO.StreamReader and System.IO.StreamWriter
read and write sequential files, respectively
5File System Organization (1)
- The Windows file system is organized
hierarchically - Physical or logical drives (A, B, C, D, etc.)
appear at the base of the hierarchy - Drive names will vary based on configuration
- Backward slash separates each directory,
subdirectory, and file - Example to create an absolute reference to
Temp.doc in the folder named C\Windows\Temp - C\Windows\Temp\Temp.doc
6File System Organization (2)
- Relative references begin with
- .\ to reference the current directory
- ..\ to reference the parent directory
- Example
- ..\Chapter.05\Complete\Temp.doc
7Current Working Directory
- One directory is considered the current working
directory - Relative directory references are made based on
the current working directory - Current working directory is ignored for absolute
directory references
8Working with the Windows File System
- System.IO.Directory has methods to manage the
file system - CreateDirectory creates a directory or
subdirectory - Delete deletes a directory or subdirectory
- Exists tests whether a directory exists
- GetCurrentDirectory gets current working
directory - GetLogicalDrives returns an array of strings
containing logical disk drives - Move method moves an existing directory to
another directory - SetCurrentDirectory sets the current working
directory
9Methods of the Directory Class (1)
- Create an absolute and relative directory
- Dim dinfoCurrent As DirectoryInfo
- dinfoCurrent Directory.CreateDirectory("C\Demo"
) - dinfoCurrent Directory.CreateDirectory("Demo")
- Delete a directory
- Directory.Delete("C\Demo")
- Directory.Delete("C\Demo", True)
- Test whether a directory exists
- Dim pblnExists As Boolean
- pblnExists Directory.Exists("C\Demo")
10Methods of the Directory Class (2)
- Get the current working directory
- Dim pstrDirectory As String
- pstrDirectory Directory.GetCurrentDirectory()
- Move a Directory
- Directory.Move("C\Demo", "C\Backup\Demo")
- Directory.Move("C\Demo", "C\Demo1")
11The File Class
- Operates similarly to the Directory class
- Has static methods to create, move, and delete
files - Copy method copies source file to destination
file - Create method creates a new file
- Delete method deletes a file
- Exists method returns a Boolean value indicating
whether the file exists - GetAttributes and SetAttributes get and set file
attributes, respectively - GetCreationTime, GetLastAccessTime, and
GetLastWriteTime get file modification information
12The File Class (Examples)
- Create a new file
- File.Create("C\Demo\DemoFile.txt")
- Copy a file
- File.Copy("C\Demo\DemoFile.txt", _
- "C\Demo\DemoFile1.txt")
- Move a file
- File.Move("C\Demo\DemoFile.txt", _
- "C\Demo\DemoFile1.txt")
- Delete a file
- File.Delete("DemoFile1.txt")
13File Attributes
- The FileAttributes enumeration contains file
attributes - Bitwise flags define each attribute
- Archive flag marks files for backup or removal
- Compressed flag is set if file is compressed
- Directory flag indicates that file is a directory
- ReadOnly flag indicates that file is marked as
read-only - System files marked with the System attribute
14Bitwise Operations
15OpenFileDialog and SaveFileDialog Controls
- Derived from the FileDialog control
- Supplies the means for the user to select a file
to open or save - OpenFileDialog
- System.Windows.Forms.OpenFileDialog
- SaveFileDialog
- System.Windows.Forms.SaveFileDialog
16OpenFileDialog and SaveFileDialog Properties (1)
- AddExtension property defines whether or not the
system adds the current file extension if omitted
by the user - The Boolean CheckFileExists and CheckPathExists
properties require the user to select a file and
directory that already exist, respectively - FileName contains the path and file name selected
by the user - FileNames contains an array of strings pertaining
to the path and name of the user selected files
17OpenFileDialog and SaveFileDialog Properties (2)
- FilterIndex and Filter properties define possible
file extensions selectable by the user and the
current file extension - InitialDirectory contains a string that defines
the directory that VB .NET will initially search
for files - MultiSelect defines whether the user can select
multiple files from the dialog boxes - If the RestoreDirectory property is set to True,
the current working directory is restored to its
original state after the dialog box is closed
18OpenFileDialog and SaveFileDialog Methods
- OpenFileDialog and SaveFileDialog support the
following public methods - ShowDialog displays the OpenFileDialog or
SaveFileDialog box - This method returns a value of type DialogResult
to indicate whether the user wants to continue
the operation - Reset sets all the properties to their default
values - FileOK event fires when the user clicks the Open
or Save button in the OpenFileDialog or
SaveFileDialog box, respectively
19OpenFileDialog (Illustration)
InitialDirectory property appears in Look in list
box
Title property appears in title bar
Filters appear in the Files of type list box
The FileName property appears in the File name
list box
20The Filter Property
- Most common file types have standard file
extensions - Word documents have a suffix of ".doc" for
example - OpenFileDialog typically restricts files to those
having a particular extension via the Filter
property - Filter property stores a String containing
description value pairs - Description and value separated by a vertical bar
- Do NOT embed spaces between description value
pairs
21The Filter Property (Example)
- Filter to select .txt and all files
ofdDemo.Filter "Text Files (.txt).txt" _
"All Files (.)."
22Reading and Writing Files
- Two types of files
- Sequential files contain records of varying
lengths - A carriage return separates each record
- A delimiter separates fields
- Comma is the common delimiter character
- Sequential files read from beginning to end
- Random files, also known as direct access files,
are typically binary files - Records in a random file have a fixed size
- Possible to read a specific record directly
23The StreamReader Class
- System.IO.StreamReader provides methods to open
sequential files for reading - Close method closes the file associated with the
StreamReader instance - You should explicitly close all files after
reading is complete - Read method reads one or more characters into a
buffer as Integer values - ReadLine method reads a line (record) into a
string - A carriage return terminates each line
- ReadToEnd method reads from the current position
in the file to the end of the file
24StreamReader Class (Examples)
- Open a file by creating an instance of the
StreamReader class - Dim pstrFileName As String "C\Demo.txt"
- Dim psrdCurrent As New System.IO.StreamReader _
(pstrFileName) - Calling the methods of the StreamReader class
allows you to read the file - Example read file from beginning to end
- txtFile.Text psrdCurrent.ReadToEnd()
25Logic to Read a Sequential File
26The Split Method
- When reading a file one record at a time, record
is read into a string - String must be split into fields
- Split method applies to the String class
- Split method returns an array of strings
27Operation of the Split Method
28The StreamWriter Class
- System.IO.StreamWriter provides methods to write
to files - Close method closes the open file
- You should explicitly close all files after
writing - Write method writes a character or characters to
the file - WriteLine method writes a character or characters
to the file - Character stored in NewLine property written to
the end of the line - NewLine property defines the character marking
the end of the line
29The StreamWriter Class
- Prepare to write to a file by creating an
instance of the StreamWriter class - Dim pstrFileName As String "C\Demo.txt"
- Dim psrdCurrent As New System.IO.StreamWriter _
- (pstrFileName)
-
30An Introduction to Collections
- A collection is nothing more than multiple
objects, typically of the same type, organized in
some logical way - Collections discussed in this chapter
- ArrayList class is similar to an array
- SortedList class maintains elements in sorted
order - Queue class implements a first-in first-out list
- Stack class works the opposite of a queue
(last-in first-out list) - There are many more collections than those
described in the preceding list
31Working with Collections
- Common members
- Count property returns the number of elements in
the collection - Count property is 1-based
- Clear method removes all of the elements from the
collection - ToArray method converts the elements in a
collection into an array - ToString method returns a String representing the
collection objects
32The ArrayList Class
- System.Collections.ArrayList
- The ArrayList class is used to maintain a list of
objects - ArrayList class has additional properties and
methods, making the ArrayList more robust than
the Array class
33ArrayList Properties
- Capacity property defines the number of elements
that the ArrayList can contain - Capacity property is updated automatically
- Capacity property grows by increasingly larger
blocks as elements are added - Count property contains the number of elements
actually stored in the ArrayList - Count is always less than Capacity
- Count property is 1-based
34ArrayList Methods (1)
- Add method adds an element to the end of the
ArrayList - AddRange method adds multiple elements to the end
of the ArrayList - BinarySearch method uses a binary search
algorithm to locate an element within a sorted
ArrayList - Remove method removes the first occurrence of a
specific element from the ArrayList
35ArrayList Methods (1)
- RemoveAt method removes an element from the
ArrayList - Method accepts one argument the 0-based index of
the element to remove - Reverse method reverses the order of the elements
stored in the ArrayList - Sort method sorts the elements in all or part of
the ArrayList
36Chapter ArrayList Implementation
37SortedList Class
- System.Collections.SortedList
- SortedList class is similar to an ArrayList in
that it stores a list of objects - SortedList class internally maintains two arrays
- First array stores the keys used to locate the
values associated with those keys - Second array stores the values that are
associated with the keys - Values can be any object type
38Implementation of a SortedList
39SortedList Methods and Properties (1)
- Add method adds an element to the SortedList
- One argument contains the key
- Another contains the index value associated with
the key - GetByIndex method gets the value associated with
the associated index - SetByIndex method stores a value based on a
specific index - Item method retrieves a value from the list given
a specific key
40SortedList Methods and Properties (2)
- Remove method removes an item from the SortedList
- Method accepts one argument the key to remove
- RemoveAt method removes an item from the
SortedList - Accepts one argument the index of the key to
remove - Values property contains a collection
- Each element in the collection represents an
object in the collection
41SortedList Examples (1)
- Locating an item in a SortedList
- Public Function FindRequest(ByVal ID As String)_
- As CallRecord
- Return CType(slRecords.Item(ID),
CallRecord) - End Function
- Adding an item to a SortedList
- Dim cr As New CallRecord()
- slRecords.Add(cr.ID, cr)
42SortedList Examples (2)
- Modifying a SortedList
- slRecords.SetByIndex(slRecords.IndexOfKey(cr.ID),
_ cr) - Removing a SortedList
- slRecords.RemoveAt(slRecords.IndexOfKey(cr.ID))
43Queue Class
- System.Collections.Queue
- A queue stores a list of objects much like an
ArrayList stores a list of objects - Queues are first-in first-out data structures
- The first item added to a queue is the first item
removed from the queue
44Operation of a Queue
45Queue Methods and Properties
- Dequeue method returns the element at the front
of the queue and removes that element from the
queue - Enqueue method adds an element to the back of the
queue - Peek method returns the element at the front of
the queue but does not remove the element from
the queue - Count property gets the number of elements stored
in the queue
46Stack Class
- System.Collections.Stack
- A stack is a last-in first-out list
- The item most recently added to the stack is the
first item removed from the stack
47Operation of a Stack
48Stack Methods and Properties
- Push method adds an item to the stack
- Pop method returns the most recently added item
from stack - The item returned is also removed from the stack
- Peek method returns the object at the top of the
stack without removing it - Count property contains the number of elements in
the stack
49Opening, Reading, and Writing Random Files
- Characteristics
- To open a random file for reading and writing,
call the FileOpen function - Records in a random file have a fixed length
- While a random file is open, any record can be
read or written - FileGet function reads a record
- FilePut function writes a record
- Seek method locates a record
50Random Files and Strings
- Strings in random files must have the same size
- Fixed length strings
- Use attribute to declare a fixed length string
Private Structure Employeef Public EmployeeID
As Integer ltVBFixedString(20)gt Public
FirstName As String ltVBFixedString(20)gt
Public LastName As String Public
AccruedVacation As Integer Public AccruedSick
As Integer End Structure
51Opening Random Files
- Before reading or writing the records contained
in a random file, it must be opened - FileOpen function opens a file for random access
- First argument contains unique file number
- Second argument contains file name
- Third argument contains access mode
- RecordLength argument defines the length of each
record
52Opening Random Files (Example)
- Open a random file
- File name stored in ofdRandom.FileName
FileOpen(1, ofdRandom.FileName, OpenMode.Random,
_ OpenAccess.Default, , Len(EmpCurrent))
53Reading andWriting Records in Random Files
- Read and write records after defining the
structure of each record in the random access
file - FilePut function writes a record to a random file
- Filenumber argument contains a valid file number
- File number obtained when the file was opened
with the FileOpen function - Value argument contains the data to be written
- Recordnumber (optional) argument contains the
record number to write. - Argument is one-based