CSharp - Chapter 17, Files and Streams

Download Report

Transcript CSharp - Chapter 17, Files and Streams

1
Chapter 17 – Files and Streams
Outline
17.1
17.2
17.3
17.4
17.5
17.6
17.7
17.8
17.9
17.10
17.11
Introduction
Data Hierarchy
Files and Streams
Classes File and Directory
Creating a Sequential-Access File
Reading Data from a Sequential-Access File
Random-Access Files
Creating a Random-Access File
Writing Data Randomly to a Random-Access File
Reading Data Sequentially from a Random-Access File
Case Study: A Transaction-Processing Program
 2002 Prentice Hall. All rights reserved.
2
17.2 Data Hierarchy
Sally
Black
Tom
Blue
Judy
Green
Iris
Orange
Randy
Red
Judy
Green
Judy
Field
01001010
1
bit
Fig. 17.1 Data hierarchy.
 2002 Prentice Hall. All rights reserved.
byte (ASCII for J)
file
record
3
17.2 Data Hierarchy
1
2
3
4
5
6
7
8
9
……
n-1
end of file marker
Fig. 17.2 C#’s view of an n-byte file.
 2002 Prentice Hall. All rights reserved.
4
17.4 Classes File and Directory
static Me tho d
De sc rip tio n
AppendText
Returns a StreamWriter that appends to an existing file or
creates a file if one does not exist.
Copy
Copies a file to a new file.
Create
Creates a file and returns its associated FileStream .
CreateText
Creates a text file and returns its associated StreamWriter .
Delete
Deletes the specified file.
GetCreationTime
Returns a DateTime object representing the time that the file was
created.
GetLastAccessTime
Returns a DateTime object representing the time that the file was
last accessed.
GetLastWriteTime
Returns a DateTime object representing the time that the file was
last modified.
Move
Moves the specified file to a specified location.
Open
Returns a FileStream associated with the specified file and
equipped with the specified read/write permissions.
OpenRead
Returns a read-only FileStream associated with the specified
file.
Returns a StreamReader associated with the specified file.
OpenText
OpenWrite
Fig. 17.3
Returns a read/write FileStream associated with the specified
file.
File c la ss m e tho d s (p a rtia l list).
 2002 Prentice Hall. All rights reserved.
5
17.4 Classes File and Directory
static Me thod
De sc rip tio n
CreateDirectory
Creates a directory and returns its associated DirectoryInfo .
Delete
Deletes the specified directory.
Exists
Returns true if the specified directory exists; otherwise, it
returns false .
GetLastWriteTime
Returns a DateTime object representing the time that the
directory was last modified.
GetDirectories
Returns a string array representing the names of the
subdirectories in the specified directory.
GetFiles
Returns a string array representing the names of the files in
the specified directory.
GetCreationTime
Returns a DateTime object representing the time that the
directory was created.
GetLastAccessTime
Returns a DateTime object representing the time that the
directory was last accessed.
GetLastWriteTime
Returns a DateTime object representing the time that items
were last written to the directory.
Move
Moves the specified directory to a specified location.
Fig. 17.4
Directory c la ss m e tho d s (p a rtia l list).
 2002 Prentice Hall. All rights reserved.
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Fig 17.5: FileTest.cs
// Using classes File and Directory.
using
using
using
using
using
using
using
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
Outline
FileTest.cs
// displays contents of files and directories
public class FileTestForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label directionsLabel;
private System.Windows.Forms.TextBox outputTextBox;
private System.Windows.Forms.TextBox inputTextBox;
private System.ComponentModel.Container components = null;
[STAThread]
static void Main()
{
Application.Run( new FileTestForm() );
}
// Visual Studio .NET generated code
// invoked when user presses key
private void inputTextBox_KeyDown(
object sender, System.Windows.Forms.KeyEventArgs e )
{
 2002 Prentice Hall.
All rights reserved.
7
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// determine whether user pressed Enter key
if ( e.KeyCode == Keys.Enter )
{
string fileName; // name of file or directory
Outline
FileTest.cs
// get user-specified file or directory
fileName = inputTextBox.Text;
// determine whether fileName is a file
if ( File.Exists( fileName ) )
{
// get file's creation date,
// modification date, etc.
outputTextBox.Text = GetInformation( fileName );
// display file contents through StreamReader
try
{
// obtain reader and file contents
StreamReader stream = new StreamReader( fileName );
outputTextBox.Text += stream.ReadToEnd();
}
// handle exception if StreamReader is unavailable
catch( IOException )
{
MessageBox.Show( "File Error", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
// determine whether fileName is a directory
else if ( Directory.Exists( fileName ) )
{
// array for directories
string[] directoryList;
 2002 Prentice Hall.
All rights reserved.
8
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// get directory's creation date,
// modification date, etc.
outputTextBox.Text = GetInformation( fileName );
Outline
FileTest.cs
// obtain file/directory list of specified directory
directoryList = Directory.GetDirectories( fileName );
outputTextBox.Text +=
"\r\n\r\nDirectory contents:\r\n";
// output directoryList contents
for ( int i = 0; i < directoryList.Length; i++ )
outputTextBox.Text += directoryList[ i ] + "\r\n";
}
else
{
// notify user that neither file nor directory exists
MessageBox.Show( inputTextBox.Text +
" does not exist", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
} // end if
} // end method inputTextBox_KeyDown
// get information on file or directory
private string GetInformation( string fileName )
{
// output that file or directory exists
string information = fileName + " exists\r\n\r\n";
// output when file or directory was created
information += "Created: " +
File.GetCreationTime( fileName ) + "\r\n";
 2002 Prentice Hall.
All rights reserved.
9
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// output when file or directory was last modified
information += "Last modified: " +
File.GetLastWriteTime( fileName ) + "\r\n";
Outline
FileTest.cs
// output when file or directory was last accessed
information += "Last accessed: " +
File.GetLastAccessTime( fileName ) + "\r\n" + "\r\n";
return information;
} // end method GetInformation
} // end class FileTestForm
 2002 Prentice Hall.
All rights reserved.
10
Outline
FileTest.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig 17.6: FileSearch.cs
// Using regular expressions to determine file types.
using
using
using
using
using
using
using
using
using
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
System.Text.RegularExpressions;
System.Collections.Specialized;
Outline
FileSearch.cs
public class FileSearchForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label directionsLabel;
private System.Windows.Forms.Label directoryLabel;
private System.Windows.Forms.Button searchButton;
private System.Windows.Forms.TextBox outputTextBox;
private System.Windows.Forms.TextBox inputTextBox;
private System.ComponentModel.Container components = null;
string currentDirectory = Directory.GetCurrentDirectory();
string[] directoryList; // subdirectories
string[] fileArray;
// store extensions found and number found
NameValueCollection found = new NameValueCollection();
 2002 Prentice Hall.
All rights reserved.
12
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
[STAThread]
static void Main()
{
Application.Run( new FileSearchForm() );
}
Outline
FileSearch.cs
// Visual Studio .NET generated code
// invoked when user types in text box
private void inputTextBox_KeyDown(
object sender, System.Windows.Forms.KeyEventArgs e )
{
// determine whether user pressed Enter
if ( e.KeyCode == Keys.Enter )
searchButton_Click( sender, e );
} // end method inputTextBox_KeyDown
// invoked when user clicks "Search Directory" button
private void searchButton_Click(
object sender, System.EventArgs e )
{
// check for user input; default is current directory
if ( inputTextBox.Text != "" )
{
// verify that user input is valid directory name
if ( Directory.Exists( inputTextBox.Text ) )
{
currentDirectory = inputTextBox.Text;
// reset input text box and update display
directoryLabel.Text = "Current Directory:" +
"\r\n" + currentDirectory;
}
 2002 Prentice Hall.
All rights reserved.
13
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
else
{
// show error if user does not specify valid directory
MessageBox.Show( "Invalid Directory", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Outline
FileSearch.cs
}
// clear text boxes
inputTextBox.Clear();
outputTextBox.Clear();
// search directory
SearchDirectory( currentDirectory );
// summarize and print results
foreach ( string current in found )
{
outputTextBox.Text += "* Found " +
found[ current ] + " " + current + " files.\r\n";
}
// clear output for new search
found.Clear();
} // end method searchButton_Click
// search directory using regular expression
private void SearchDirectory( string currentDirectory )
{
// search directory
try
{
string fileName = "";
 2002 Prentice Hall.
All rights reserved.
14
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// regular expression for extensions matching pattern
Regex regularExpression = new Regex(
"[a-zA-Z0-9]+\\.(?<extension>\\w+)" );
// stores regular-expression-match result
Match matchResult;
Outline
FileSearch.cs
string fileExtension; // holds file extensions
// number of files with given extension in directory
int extensionCount;
// get directories
directoryList =
Directory.GetDirectories( currentDirectory );
// get list of files in current directory
fileArray = Directory.GetFiles( currentDirectory );
// iterate through list of files
foreach ( string myFile in fileArray )
{
// remove directory path from file name
fileName = myFile.Substring(
myFile.LastIndexOf( "\\" ) + 1 );
// obtain result for regular-expression search
matchResult = regularExpression.Match( fileName );
// check for match
if ( matchResult.Success )
fileExtension =
matchResult.Result( "${extension}" );
 2002 Prentice Hall.
All rights reserved.
15
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
else
fileExtension = "[no extension]";
// store value from container
if ( found[ fileExtension ] == null )
found.Add( fileExtension, "1" );
else
{
extensionCount = Int32.Parse(
found[ fileExtension ] ) + 1;
Outline
FileSearch.cs
found[ fileExtension ] = extensionCount.ToString();
}
// search for backup(.bak) files
if ( fileExtension == "bak" )
{
// prompt user to delete (.bak) file
DialogResult result =
MessageBox.Show( "Found backup file " +
fileName + ". Delete?", "Delete Backup",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question );
// delete file if user clicked 'yes'
if ( result == DialogResult.Yes )
{
File.Delete( myFile );
extensionCount =
Int32.Parse( found[ "bak" ] ) - 1;
 2002 Prentice Hall.
All rights reserved.
16
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
found[ "bak" ] = extensionCount.ToString();
}
Outline
}
}
FileSearch.cs
// recursive call to search files in subdirectory
foreach ( string myDirectory in directoryList )
SearchDirectory( myDirectory );
}
// handle exception if files have unauthorized access
catch( UnauthorizedAccessException )
{
MessageBox.Show( "Some files may not be visible" +
" due to permission settings", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Information );
}
} // end method SearchDirectory
} // end class FileSearchForm
 2002 Prentice Hall.
All rights reserved.
17
Outline
FileSearch.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig 17.7: BankUI.cs
// A reusable windows form for the examples in this chapter.
using
using
using
using
using
using
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
Outline
BankUI.cs
public class BankUIForm : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
public System.Windows.Forms.Label accountLabel;
public System.Windows.Forms.TextBox accountTextBox;
public System.Windows.Forms.Label firstNameLabel;
public System.Windows.Forms.TextBox firstNameTextBox;
public System.Windows.Forms.Label lastNameLabel;
public System.Windows.Forms.TextBox lastNameTextBox;
public System.Windows.Forms.Label balanceLabel;
public System.Windows.Forms.TextBox balanceTextBox;
// number of TextBoxes on Form'
protected int TextBoxCount = 4;
 2002 Prentice Hall.
All rights reserved.
19
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// enumeration constants specify TextBox indices
public enum TextBoxIndices
{
ACCOUNT,
FIRST,
LAST,
BALANCE
Outline
BankUI.cs
} // end enum
[STAThread]
static void Main()
{
Application.Run( new BankUIForm() );
}
// Visual Studio .NET generated code
// clear all TextBoxes
public void ClearTextBoxes()
{
// iterate through every Control on form
for ( int i = 0; i < Controls.Count; i++ )
{
Control myControl = Controls[ i ]; // get control
// determine whether Control is TextBox
if ( myControl is TextBox )
{
// clear Text property (set to empty strng)
myControl.Text = "";
}
}
} // end method ClearTextBoxes
 2002 Prentice Hall.
All rights reserved.
20
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// set text box values to string array values
public void SetTextBoxValues( string[] values )
{
// determine whether string array has correct length
if ( values.Length != TextBoxCount )
{
// throw exception if not correct length
throw( new ArgumentException( "There must be " +
(TextBoxCount + 1) + " strings in the array" ) );
}
Outline
BankUI.cs
// set array values if array has correct length
else
{
// set array values to text box values
accountTextBox.Text =
values[ ( int )TextBoxIndices.ACCOUNT ];
firstNameTextBox.Text =
values[ ( int )TextBoxIndices.FIRST ];
lastNameTextBox.Text =
values[ ( int )TextBoxIndices.LAST ];
balanceTextBox.Text =
values[ ( int )TextBoxIndices.BALANCE ];
}
} // end method SetTextBoxValues
// return text box values as string array
public string[] GetTextBoxValues()
{
string[] values = new string[ TextBoxCount ];
 2002 Prentice Hall.
All rights reserved.
21
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// copy text box fields to string array
values[ ( int )TextBoxIndices.ACCOUNT ] =
accountTextBox.Text;
values[ ( int )TextBoxIndices.FIRST ] =
firstNameTextBox.Text;
values[ ( int )TextBoxIndices.LAST ] =
lastNameTextBox.Text;
values[ ( int )TextBoxIndices.BALANCE ] =
balanceTextBox.Text;
Outline
BankUI.cs
return values;
} // end method GetTextBoxValues
} // end class BankUIForm
Program Output
 2002 Prentice Hall.
All rights reserved.
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 17.8: Record.cs
// Serializable class that represents a data record.
using System;
Outline
Record.cs
[Serializable]
public class Record
{
private int account;
private string firstName;
private string lastName;
private double balance;
// default constructor sets members to default values
public Record() : this( 0, "", "", 0.0 )
{
}
// overloaded constructor sets members to parameter values
public Record( int accountValue, string firstNameValue,
string lastNameValue, double balanceValue )
{
Account = accountValue;
FirstName = firstNameValue;
LastName = lastNameValue;
Balance = balanceValue;
} // end constructor
 2002 Prentice Hall.
All rights reserved.
23
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// property Account
public int Account
{
get
{
return account;
}
Outline
Record.cs
set
{
account = value;
}
} // end property Account
// property FirstName
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
} // end property FirstName
 2002 Prentice Hall.
All rights reserved.
24
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// property LastName
public string LastName
{
get
{
return lastName;
}
Outline
Record.cs
set
{
lastName = value;
}
} // end property LastName
// property Balance
public double Balance
{
get
{
return balance;
}
set
{
balance = value;
}
} // end property Balance
} // end class Record
 2002 Prentice Hall.
All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig 17.9: CreateSequentialAccessFile.cs
// Creating a sequential-access file.
// C#
using
using
using
using
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
System.Runtime.Serialization.Formatters.Binary;
System.Runtime.Serialization;
Outline
CreateSequential
AccessFile.cs
// Deitel namespace
using BankLibrary;
public class CreateFileForm : BankUIForm
{
private System.Windows.Forms.Button saveButton;
private System.Windows.Forms.Button enterButton;
private System.Windows.Forms.Button exitButton;
private System.ComponentModel.Container components = null;
// serializes Record in binary format
private BinaryFormatter formatter = new BinaryFormatter();
// stream through which serializable data is written to file
private FileStream output;
 2002 Prentice Hall.
All rights reserved.
26
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
[STAThread]
static void Main()
{
Application.Run( new CreateFileForm() );
}
Outline
CreateSequential
AccessFile.cs
// Visual Studio .NET generated code
// invoked when user clicks Save button
private void saveButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to save file
SaveFileDialog fileChooser = new SaveFileDialog();
DialogResult result = fileChooser.ShowDialog();
string fileName; // name of file to save data
// allow user to create file
fileChooser.CheckFileExists = false;
// exit event handler if user clicked "Cancel"
if ( result == DialogResult.Cancel )
return;
// get specified file name
fileName = fileChooser.FileName;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show( "Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
 2002 Prentice Hall.
All rights reserved.
27
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
else
{
// save file via FileStream if user specified valid file
try
{
// open file with write access
output = new FileStream( fileName,
FileMode.OpenOrCreate, FileAccess.Write );
Outline
CreateSequential
AccessFile.cs
// disable Save button and enable Enter button
saveButton.Enabled = false;
enterButton.Enabled = true;
}
// handle exception if file does not exist
catch ( FileNotFoundException )
{
// notify user if file does not exist
MessageBox.Show( "File Does Not Exist", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
} // end method saveButton_Click
// invoke when user clicks Enter button
private void enterButton_Click(
object sender, System.EventArgs e )
{
// store TextBox values string array
string[] values = GetTextBoxValues();
// Record containing TextBox values to serialize
Record record = new Record();
 2002 Prentice Hall.
All rights reserved.
28
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// determine whether TextBox account field is empty
if ( values[ ( int )TextBoxIndices.ACCOUNT ] != "" )
{
// store TextBox values in Record and serialize Record
try
{
// get account number value from TextBox
int accountNumber = Int32.Parse(
values[ ( int )TextBoxIndices.ACCOUNT ] );
Outline
CreateSequential
AccessFile.cs
// determine whether accountNumber is valid
if ( accountNumber > 0 )
{
// store TextBox fields in Record
record.Account = accountNumber;
record.FirstName =
values[ ( int )TextBoxIndices.FIRST ];
record.LastName =
values[ ( int )TextBoxIndices.LAST ];
record.Balance = Double.Parse( values[
( int )TextBoxIndices.BALANCE ] );
// write Record to FileStream (serialize object)
formatter.Serialize( output, record );
}
else
{
// notify user if invalid account number
MessageBox.Show( "Invalid Account Number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
 2002 Prentice Hall.
All rights reserved.
29
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// notify user if error occurs in serialization
catch( SerializationException )
{
MessageBox.Show( "Error Writing to File", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Outline
CreateSequential
AccessFile.cs
// notify user if error occurs regarding parameter format
catch( FormatException )
{
MessageBox.Show( "Invalid Format", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
ClearTextBoxes(); // clear TextBox values
} // end method enterButton_Click
// invoked when user clicks Exit button
private void exitButton_Click(
object sender, System.EventArgs e )
{
// determine whether file exists
if ( output != null )
{
// close file
try
{
output.Close();
}
 2002 Prentice Hall.
All rights reserved.
30
162
163
164
165
166
167
168
169
170
171
172
173
174
// notify user of error closing file
catch( IOException )
{
MessageBox.Show( "Cannot close file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Outline
CreateSequential
AccessFile.cs
}
Application.Exit();
} // end method exitButton_Click
} // end class CreateFileForm
Program Output
BankUI graphical
user interface
 2002 Prentice Hall.
All rights reserved.
31
Outline
CreateSequential
AccessFile.cs
Program Output
SaveFileDialogue
Files and directories
 2002 Prentice Hall.
All rights reserved.
32
Outline
CreateSequential
AccessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
33
Outline
CreateSequential
AccessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
34
Outline
CreateSequential
AccessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
35
17.5 Creating a Sequential-Access File
Ac c ount Numb er
First Na me
La st Na me
Ba la nc e
100
Nancy
Brown
-25.54
200
Stacey
Dunn
314.33
300
Doug
Barker
0.00
400
Dave
Smith
258.34
500
Sam
Stone
34.98
Fig. 17.10
Sa mp le d a ta for the p rog ra m of Fig. 17.9.
 2002 Prentice Hall. All rights reserved.
36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 17.11: ReadSequentialAccessFile.cs
// Reading a sequential-access file.
// C#
using
using
using
using
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
System.Runtime.Serialization.Formatters.Binary;
System.Runtime.Serialization;
Outline
ReadSequentialAc
cessFile.cs
// Deitel namespaces
using BankLibrary;
public class ReadSequentialAccessFileForm : BankUIForm
{
System.Windows.Forms.Button openButton;
System.Windows.Forms.Button nextButton;
private System.ComponentModel.Container components = null;
// stream through which serializable data are read from file
private FileStream input;
// object for deserializing Record in binary format
private BinaryFormatter reader = new BinaryFormatter();
[STAThread]
static void Main()
{
Application.Run( new ReadSequentialAccessFileForm() );
}
 2002 Prentice Hall.
All rights reserved.
37
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Visual Studio .NET generated code
// invoked when user clicks Open button
private void openButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to open file
OpenFileDialog fileChooser = new OpenFileDialog();
DialogResult result = fileChooser.ShowDialog();
string fileName; // name of file containing data
Outline
ReadSequentialAc
cessFile.cs
// exit event handler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// get specified file name
fileName = fileChooser.FileName;
ClearTextBoxes();
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show( "Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
else
{
// create FileStream to obtain read access to file
input = new FileStream( fileName, FileMode.Open,
FileAccess.Read );
// enable next record button
nextButton.Enabled = true;
}
} // end method openButton_Click
 2002 Prentice Hall.
All rights reserved.
38
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// invoked when user clicks Next button
private void nextButton_Click(
object sender, System.EventArgs e )
{
// deserialize Record and store data in TextBoxes
try
{
// get next Record available in file
Record record =
( Record )reader.Deserialize( input );
Outline
ReadSequentialAc
cessFile.cs
// store Record values in temporary string array
string[] values = new string[] {
record.Account.ToString(),
record.FirstName.ToString(),
record.LastName.ToString(),
record.Balance.ToString() };
// copy string array values to TextBox values
SetTextBoxValues( values );
}
// handle exception when no Records in file
catch( SerializationException )
{\
// close FileStream if no Records in file
input.Close();
// enable Open Record button
openButton.Enabled = true;
// disable Next Record button
nextButton.Enabled = false;
 2002 Prentice Hall.
All rights reserved.
39
106
107
108
109
110
111
112
113
114
115
ClearTextBoxes();
// notify user if no Records in file
MessageBox.Show( "No more records in file", "",
MessageBoxButtons.OK, MessageBoxIcon.Information );
}
Outline
ReadSequentialAc
cessFile.cs
} // end method nextButton_Click
} // end class ReadSequentialAccessFileForm
Program Output
 2002 Prentice Hall.
All rights reserved.
40
Outline
ReadSequentialAc
cessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
41
Outline
ReadSequentialAc
cessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
42
Outline
ReadSequentialAc
cessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
43
Outline
ReadSequentialAc
cessFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 17.12: CreditInquiry.cs
// Read a file sequentially and display contents based on
// account type specified by user (credit, debit or zero balances).
// C#
using
using
using
using
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
System.Runtime.Serialization.Formatters.Binary;
System.Runtime.Serialization;
Outline
CreditInquiry.cs
// Deitel namespaces
using BankLibrary;
public class CreditInquiryForm : System.Windows.Forms.Form
{
private System.Windows.Forms.RichTextBox displayTextBox;
private
private
private
private
private
System.Windows.Forms.Button
System.Windows.Forms.Button
System.Windows.Forms.Button
System.Windows.Forms.Button
System.Windows.Forms.Button
doneButton;
zeroButton;
debitButton;
creditButton;
openButton;
private System.ComponentModel.Container components = null;
// stream through which serializable data are read from file
private FileStream input;
// object for deserializing Record in binary format
BinaryFormatter reader = new BinaryFormatter();
 2002 Prentice Hall.
All rights reserved.
45
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// name of file that stores credit, debit and zero balances
private string fileName;
[STAThread]
static void Main()
{
Application.Run( new CreditInquiryForm() );
}
Outline
CreditInquiry.cs
// Visual Studio .NET generated code
// invoked when user clicks Open File button
private void openButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to open file
OpenFileDialog fileChooser = new OpenFileDialog();
DialogResult result = fileChooser.ShowDialog();
// exit event handler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// get name from user
fileName = fileChooser.FileName;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show( "Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
 2002 Prentice Hall.
All rights reserved.
46
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
else
{
// enable all GUI buttons, except for Open file button
openButton.Enabled = false;
creditButton.Enabled = true;
debitButton.Enabled = true;
zeroButton.Enabled = true;
}
Outline
CreditInquiry.cs
} // end method openButton_Click
// invoked when user clicks credit balances,
// debit balances or zero balances button
private void get_Click( object sender, System.EventArgs e )
{
// convert sender explicitly to object of type button
Button senderButton = ( Button )sender;
// get text from clicked Button, which stores account type
string accountType = senderButton.Text;
// read and display file information
try
{
// close file from previous operation
if ( input != null )
input.Close();
// create FileStream to obtain read access to file
input = new FileStream( fileName, FileMode.Open,
FileAccess.Read );
displayTextBox.Text = "The accounts are:\r\n";
 2002 Prentice Hall.
All rights reserved.
47
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// traverse file until end of file
while ( true )
{
// get next Record available in file
Record record = ( Record )reader.Deserialize( input );
Outline
CreditInquiry.cs
// store record's last field in balance
Double balance = record.Balance;
// determine whether to display balance
if ( ShouldDisplay( balance, accountType ) )
{
// display record
string output = record.Account + "\t" +
record.FirstName + "\t" + record.LastName +
new string( ' ', 6 ) + "\t";
// display balance with correct monetary format
output += String.Format(
"{0:F}", balance ) + "\r\n";
// copy output to screen
displayTextBox.Text += output;
}
}
}
// handle exception when file cannot be closed
catch( IOException )
{
MessageBox.Show( "Cannot Close File", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
 2002 Prentice Hall.
All rights reserved.
48
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// handle exception when no more records
catch( SerializationException )
{
// close FileStream if no Records in file
input.Close();
}
Outline
CreditInquiry.cs
} // end method get_Click
// determine whether to display given record
private bool ShouldDisplay( double balance, string accountType )
{
if ( balance > 0 )
{
// display credit balances
if ( accountType == "Credit Balances" )
return true;
}
else if ( balance < 0 )
{
// display debit balances
if ( accountType == "Debit Balances" )
return true;
}
else // balance == 0
{
// display zero balances
if ( accountType == "Zero Balances" )
return true;
}
 2002 Prentice Hall.
All rights reserved.
49
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
return false;
Outline
} // end method ShouldDisplay
// invoked when user clicks Done button
private void doneButton_Click(
object sender, System.EventArgs e )
{
// determine whether file exists
if ( input != null )
{
// close file
try
{
input.Close();
}
CreditInquiry.cs
// handle exception if FileStream does not exist
catch( IOException )
{
// notify user of error closing file
MessageBox.Show( "Cannot close file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Application.Exit();
} // end method doneButton_Click
} // end class CreditInquiryForm
 2002 Prentice Hall.
All rights reserved.
50
Outline
CreditInquiry.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
51
Outline
CreditInquiry.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
52
17.7 Random-Access Files
0
100
200
300
400
500
byte offsets
100
bytes
100
bytes
100
bytes
100
bytes
100
bytes
Fig. 17.13 Random-access file with fixed-length records.
 2002 Prentice Hall. All rights reserved.
100
bytes
53
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 17.14: RandomAccessRecord.cs
// Data-record class for random-access applications.
using System;
public class RandomAccessRecord
{
// length of firstName and lastName
private const int CHAR_ARRAY_LENGTH = 15;
Outline
RandomAccessReco
rd.cs
private const int SIZE_OF_CHAR = 2;
private const int SIZE_OF_INT32 = 4;
private const int SIZE_OF_DOUBLE = 8;
// length of record
public const int SIZE = SIZE_OF_INT32 +
2 * ( SIZE_OF_CHAR * CHAR_ARRAY_LENGTH ) + SIZE_OF_DOUBLE;
// record data
private int account;
private char[] firstName = new char[ CHAR_ARRAY_LENGTH ];
private char[] lastName = new char[ CHAR_ARRAY_LENGTH ];
private double balance;
// default constructor sets members to default values
public RandomAccessRecord() : this( 0, "", "", 0.0 )
{
}
 2002 Prentice Hall.
All rights reserved.
54
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// overloaded counstructor sets members to parameter values
public RandomAccessRecord( int accountValue,
string firstNameValue, string lastNameValue,
double balanceValue )
{
Account = accountValue;
FirstName = firstNameValue;
LastName = lastNameValue;
Balance = balanceValue;
Outline
RandomAccessReco
rd.cs
} // end constructor
// property Account
public int Account
{
get
{
return account;
}
set
{
account = value;
}
} // end property Account
// property FirstName
public string FirstName
{
get
{
return new string( firstName );
}
 2002 Prentice Hall.
All rights reserved.
55
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Outline
set
{
// determine length of string parameter
int stringSize = value.Length;
// firstName string representation
string firstNameString = value;
RandomAccessReco
rd.cs
// append spaces to string parameter if too short
if ( CHAR_ARRAY_LENGTH >= stringSize )
{
firstNameString = value +
new string( ' ', CHAR_ARRAY_LENGTH - stringSize );
}
else
{
// remove characters from string parameter if too long
firstNameString =
value.Substring( 0, CHAR_ARRAY_LENGTH );
}
// convert string parameter to char array
firstName = firstNameString.ToCharArray();
} // end set
} // end property FirstName
// property LastName
public string LastName
{
get
{
return new string( lastName );
}
 2002 Prentice Hall.
All rights reserved.
56
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
Outline
set
{
// determine length of string parameter
int stringSize = value.Length;
RandomAccessReco
rd.cs
// lastName string representation
string lastNameString = value;
// append spaces to string parameter if too short
if ( CHAR_ARRAY_LENGTH >= stringSize )
{
lastNameString = value +
new string( ' ', CHAR_ARRAY_LENGTH - stringSize );
}
else
{
// remove characters from string parameter if too long
lastNameString =
value.Substring( 0, CHAR_ARRAY_LENGTH );
}
// convert string parameter to char array
lastName = lastNameString.ToCharArray();
} // end set
} // end property LastName
 2002 Prentice Hall.
All rights reserved.
57
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// property Balance
public double Balance
{
get
{
return balance;
}
Outline
RandomAccessReco
rd.cs
set
{
balance = value;
}
} // end property Balance
} // end class RandomAccessRecord
 2002 Prentice Hall.
All rights reserved.
58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Fig. 17.15: CreateRandomAccessFile.cs
// Creating a random file.
// C#
using
using
using
namespaces
System;
System.IO;
System.Windows.Forms;
Outline
CreateRandomAcce
ssFile.cs
// Deitel namespaces
using BankLibrary;
class CreateRandomAccessFile
{
// number of records to write to disk
private const int NUMBER_OF_RECORDS = 100;
[STAThread]
static void Main(string[] args)
{
// create random file, then save to disk
CreateRandomAccessFile file = new CreateRandomAccessFile();
file.SaveFile();
} // end method Main
// write records to disk
private void SaveFile()
{
// record for writing to disk
RandomAccessRecord blankRecord = new RandomAccessRecord();
// stream through which serializable data are written to file
FileStream fileOutput = null;
 2002 Prentice Hall.
All rights reserved.
59
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// stream for writing bytes to file
BinaryWriter binaryOutput = null;
// create dialog box enabling user to save file
SaveFileDialog fileChooser = new SaveFileDialog();
DialogResult result = fileChooser.ShowDialog();
Outline
CreateRandomAcce
ssFile.cs
// get file name from user
string fileName = fileChooser.FileName;
// exit event handler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show("Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
// write records to file
try
{
// create FileStream to hold records
fileOutput = new FileStream( fileName,
FileMode.Create, FileAccess.Write );
// set length of file
fileOutput.SetLength( RandomAccessRecord.SIZE *
NUMBER_OF_RECORDS );
// create object for writing bytes to file
binaryOutput = new BinaryWriter( fileOutput );
 2002 Prentice Hall.
All rights reserved.
60
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// write empty records to file
for ( int i = 0; i < NUMBER_OF_RECORDS; i++ )
{
// set file position pointer in file
fileOutput.Position = i * RandomAccessRecord.SIZE;
Outline
CreateRandomAcce
ssFile.cs
// write blank record to file
binaryOutput.Write( blankRecord.Account );
binaryOutput.Write( blankRecord.FirstName );
binaryOutput.Write( blankRecord.LastName );
binaryOutput.Write( blankRecord.Balance );
}
// notify user of success
MessageBox.Show("File Created", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// handle exception if error occurs during writing
catch( IOException )
{
// notify user of error
MessageBox.Show( "Cannot write to file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
 2002 Prentice Hall.
All rights reserved.
61
96
97
98
99
100
101
102
103
104
105
// close FileStream
if ( fileOutput == null )
fileOutput.Close();
// close BinaryWriter
if ( binaryOutput == null )
binaryOutput.Close();
Outline
CreateRandomAcce
ssFile.cs
} // end method SaveFile
} // end class CreateRandomAccessFile
Program Output
 2002 Prentice Hall.
All rights reserved.
62
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig 17.16: WriteRandomAccessFile.cs
// Write data to a random-access file.
// C#
using
using
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
Outline
WriteRandomAcces
sFile.cs
// Deitel namespaces
using BankLibrary;
public class WriteRandomAccessFileForm : BankUIForm
{
private System.Windows.Forms.Button openButton;
private System.Windows.Forms.Button enterButton;
private System.ComponentModel.Container components = null;
// number of RandomAccessRecords to write to disk
private const int NUMBER_OF_RECORDS = 100;
// stream through which data are written to file
private FileStream fileOutput;
// stream for writing bytes to file
private BinaryWriter binaryOutput;
 2002 Prentice Hall.
All rights reserved.
63
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
[STAThread]
static void Main()
{
Application.Run( new WriteRandomAccessFileForm() );
}
Outline
WriteRandomAcces
sFile.cs
// Visual Studio .NET generated code
// invoked when user clicks Open button
private void openButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to open file
OpenFileDialog fileChooser = new OpenFileDialog();
DialogResult result = fileChooser.ShowDialog();
// get file name from user
string fileName = fileChooser.FileName;
// exit event handler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show("Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
// open file if file already exists
try
{
// create FileStream to hold records
fileOutput = new FileStream( fileName,
FileMode.Open, FileAccess.Write );
 2002 Prentice Hall.
All rights reserved.
64
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// create object for writing bytes to file
binaryOutput = new BinaryWriter( fileOutput );
// disable Open button and enable Enter button
openButton.Enabled = false;
enterButton.Enabled = true;
Outline
WriteRandomAcces
sFile.cs
}
// notify user if file does not exist
catch( IOException )
{
MessageBox.Show("File Does Not Exits", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} // end method openButton_Click
// invoked when user clicks Enter button
private void enterButton_Click(
object sender, System.EventArgs e )
{
// TextBox values string array
string[] values = GetTextBoxValues();
// determine whether TextBox account field is empty
if ( values[ ( int )TextBoxIndices.ACCOUNT ] != "" )
{
// write record to file at appropriate position
try
{
// get account number value from TextBox
int accountNumber = Int32.Parse(
values[ ( int )TextBoxIndices.ACCOUNT ] );
 2002 Prentice Hall.
All rights reserved.
65
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// determine whether accountNumber is valid
if ( accountNumber > 0 &&
accountNumber <= NUMBER_OF_RECORDS )
{
// move file position pointer
fileOutput.Seek( ( accountNumber - 1 ) *
RandomAccessRecord.SIZE, SeekOrigin.Begin );
Outline
WriteRandomAcces
sFile.cs
// write data to file
binaryOutput.Write( accountNumber );
binaryOutput.Write(
values[ ( int )TextBoxIndices.FIRST ] );
binaryOutput.Write(
values[ ( int )TextBoxIndices.LAST ] );
binaryOutput.Write( Double.Parse( values[
( int )TextBoxIndices.BALANCE ] ) );
}
else
{
// notify user if invalid account number
MessageBox.Show("Invalid Account Number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// handle number-format exception
 2002 Prentice Hall.
All rights reserved.
66
129
130
131
132
133
134
135
136
137
138
139
140
141
catch( FormatException )
{
// notify user if error occurs when formatting numbers
MessageBox.Show("Invalid Balance", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Outline
WriteRandomAcces
sFile.cs
}
ClearTextBoxes(); // clear text box values
} // end method enterButton_Click
} // end class WriteRandomAccessFileForm
Program Output
 2002 Prentice Hall.
All rights reserved.
67
Outline
WriteRandomAcces
sFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
68
Outline
WriteRandomAcces
sFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
69
Outline
WriteRandomAcces
sFile.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig 17.17: ReadRandomAccessFile.cs
// Reads and displays random-access file contents.
// C#
using
using
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.IO;
Outline
ReadRandomAccess
File.cs
// Deitel namespaces
using BankLibrary;
public class ReadRandomAccessFileForm : BankUIForm
{
private System.Windows.Forms.Button openButton;
private System.Windows.Forms.Button nextButton;
private System.ComponentModel.Container components = null;
// stream through which data are read from file
private FileStream fileInput;
// stream for reading bytes from file
private BinaryReader binaryInput;
// index of current record to be displayed
private int currentRecordIndex;
 2002 Prentice Hall.
All rights reserved.
71
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
[STAThread]
static void Main()
{
Application.Run( new ReadRandomAccessFileForm() );
}
Outline
ReadRandomAccess
File.cs
// Visual Studio .NET generated code
// invoked when user clicks Open button
private void openButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to open file
OpenFileDialog fileChooser = new OpenFileDialog();
DialogResult result = fileChooser.ShowDialog();
// get file name from user
string fileName = fileChooser.FileName;
// exit eventhandler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show( "Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
else
{
// create FileStream to obtain read access to file
fileInput = new FileStream( fileName,
FileMode.Open, FileAccess.Read );
 2002 Prentice Hall.
All rights reserved.
72
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// use FileStream for BinaryWriter to read bytes from file
binaryInput = new BinaryReader( fileInput );
openButton.Enabled = false; // disable Open button
nextButton.Enabled = true; // enable Next button
Outline
ReadRandomAccess
File.cs
currentRecordIndex = 0;
ClearTextBoxes();
}
} // end method openButton_Click
// invoked when user clicks Next button
private void nextButton_Click(
object sender, System.EventArgs e )
{
// record to store file data
RandomAccessRecord record = new RandomAccessRecord();
// read record and store data in TextBoxes
try
{
string[] values; // for storing TextBox values
// get next record available in file
while( record.Account == 0 )
{
// set file position pointer to next record in file
fileInput.Seek(
currentRecordIndex * RandomAccessRecord.SIZE, 0 );
currentRecordIndex += 1;
 2002 Prentice Hall.
All rights reserved.
73
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// read data from record
record.Account = binaryInput.ReadInt32();
record.FirstName = binaryInput.ReadString();
record.LastName = binaryInput.ReadString();
record.Balance = binaryInput.ReadDouble();
}
Outline
ReadRandomAccess
File.cs
// store record values in temporary string array
values = new string[] {
record.Account.ToString(),
record.FirstName,
record.LastName,
record.Balance.ToString() };
// copy string array values to TextBox values
SetTextBoxValues( values );
}
// handle exception when no records in file
catch( IOException )
{
// close streams if no records in file
fileInput.Close();
binaryInput.Close();
openButton.Enabled = true; // enable Open button
nextButton.Enabled = false; // disable Next button
ClearTextBoxes();
 2002 Prentice Hall.
All rights reserved.
74
127
128
129
130
131
132
133
134
// notify user if no records in file
MessageBox.Show("No more records in file", "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} // end method nextButton_Click
Outline
ReadRandomAccess
File.cs
} // end class ReadRandomAccessFileForm
Program Output
 2002 Prentice Hall.
All rights reserved.
75
Outline
ReadRandomAccess
File.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
76
Outline
ReadRandomAccess
File.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
77
Outline
ReadRandomAccess
File.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
78
Outline
ReadRandomAccess
File.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
79
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Fig. 17.18: Transaction.cs
// Handles record transactions.
// C#
using
using
using
namespaces
System;
System.IO;
System.Windows.Forms;
Outline
Transaction.cs
// Deitel namespaces
using BankLibrary;
public class Transaction
{
// number of records to write to disk
private const int NUMBER_OF_RECORDS = 100;
// stream through which data move to and from file
private FileStream file;
// stream for reading bytes from file
private BinaryReader binaryInput;
// stream for writing bytes to file
private BinaryWriter binaryOutput;
// create/open file containing empty records
public void OpenFile( string fileName )
{
// write empty records to file
try
{
// create FileStream from new file or existing file
file = new FileStream( fileName, FileMode.OpenOrCreate );
 2002 Prentice Hall.
All rights reserved.
80
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// use FileStream for BinaryWriter to read bytes from file
binaryInput = new BinaryReader( file );
// use FileStream for BinaryWriter to write bytes to file
binaryOutput = new BinaryWriter( file );
Outline
Transaction.cs
// determine whether file has just been created
if ( file.Length == 0 )
{
// record to be written to file
RandomAccessRecord blankRecord =
new RandomAccessRecord();
// new record can hold NUMBER_OF_RECORDS records
file.SetLength( RandomAccessRecord.SIZE *
NUMBER_OF_RECORDS );
// write blank records to file
for ( int i = 0; i < NUMBER_OF_RECORDS; i++ )
{
// move file-position pointer to next position
file.Position = i * RandomAccessRecord.SIZE;
// write blank record to file
binaryOutput.Write( blankRecord.Account );
binaryOutput.Write( blankRecord.FirstName );
binaryOutput.Write( blankRecord.LastName );
binaryOutput.Write( blankRecord.Balance );
}
}
}
 2002 Prentice Hall.
All rights reserved.
81
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// notify user of error during writing of blank records
catch( IOException )
{
MessageBox.Show("Cannot create file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Outline
Transaction.cs
} // end method OpenFile
// retrieve record depending on whether account is valid
public RandomAccessRecord GetRecord( string accountValue )
{
// store file data associated with account in record
try
{
// record to store file data
RandomAccessRecord record = new RandomAccessRecord();
// get value from TextBox's account field
int accountNumber = Int32.Parse( accountValue );
// if account is invalid, do not read data
if ( accountNumber < 1 ||
accountNumber > NUMBER_OF_RECORDS )
{
// set record's account field with account number
record.Account = accountNumber;
}
// get data from file if account is valid
else
{
// locate position in file where record exists
file.Seek( ( accountNumber - 1 ) *
RandomAccessRecord.SIZE, 0 );
 2002 Prentice Hall.
All rights reserved.
82
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// read data from record
record.Account = binaryInput.ReadInt32();
record.FirstName = binaryInput.ReadString();
record.LastName = binaryInput.ReadString();
record.Balance = binaryInput.ReadDouble();
Outline
Transaction.cs
}
return record;
}
// notify user of error during reading
catch( IOException )
{
MessageBox.Show( "Cannot read file", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
return null;
} // end method GetRecord;
// add record to file at position determined by accountNumber
public bool AddRecord(
RandomAccessRecord record, int accountNumber )
{
// write record to file
try
{
// move file position pointer to appropriate position
file.Seek( ( accountNumber - 1 ) *
RandomAccessRecord.SIZE, 0 );
 2002 Prentice Hall.
All rights reserved.
83
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// write data to file
binaryOutput.Write(record.Account);
binaryOutput.Write(record.FirstName);
binaryOutput.Write(record.LastName);
binaryOutput.Write(record.Balance);
Outline
Transaction.cs
}
// notify user if error occurs during writing
catch( IOException )
{
MessageBox.Show( "Error Writing To File", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
return false; // failure
}
return true; // success
} // end method AddRecord
} // end class Transaction
 2002 Prentice Hall.
All rights reserved.
84
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 17.19: TransactionProcessor.cs
// MDI parent for transaction-processor application.
using
using
using
using
using
using
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
Outline
TransactionProce
ssor.cs
public class TransactionProcessorForm
: System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.MdiClient MdiClient1;
// reference to StartDialog
private StartDialogForm startDialog;
// constructor
public TransactionProcessorForm()
{
// required for Windows Form Designer support
InitializeComponent();
startDialog = new StartDialogForm();
startDialog.MdiParent = this;
startDialog.Show();
}
 2002 Prentice Hall.
All rights reserved.
85
31
32
33
34
35
36
37
38
39
[STAThread]
static void Main()
{
Application.Run( new TransactionProcessorForm() );
}
Outline
TransactionProce
ssor.cs
// Visual Studio .NET generated code
} // end class TransactionProcessorForm
 2002 Prentice Hall.
All rights reserved.
86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
//
//
//
Fig. 17.20: StartDialog.cs
Initial dialog box displayed to user. Provides buttons for
creating/opening file and for adding, updating and removing
records from file.
// C#
using
using
using
using
using
Outline
StartDialog.cs
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
// Deitel namespaces
using BankLibrary;
public delegate void MyDelegate();
public class StartDialogForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button updateButton;
private System.Windows.Forms.Button newButton;
private System.Windows.Forms.Button deleteButton;
private System.Windows.Forms.Button openButton;
private System.ComponentModel.Container components = null;
// reference to dialog box for adding record
private NewDialogForm newDialog;
// reference to dialog box for updating record
private UpdateDialogForm updateDialog;
// reference to dialog box for removing record
private DeleteDialogForm deleteDialog;
 2002 Prentice Hall.
All rights reserved.
87
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// reference to object that handles transactions
private Transaction transactionProxy;
// Visual Studio .NET generated code
Outline
StartDialog.cs
// invoked when user clicks New/Open File button
private void openButton_Click(
object sender, System.EventArgs e )
{
// create dialog box enabling user to create or open file
OpenFileDialog fileChooser = new OpenFileDialog();
DialogResult result;
string fileName;
// enable user to create file if file does not exist
fileChooser.Title = "Create File / Open File";
fileChooser.CheckFileExists = false;
// show dialog box to user
result = fileChooser.ShowDialog();
// exit event handler if user clicked Cancel
if ( result == DialogResult.Cancel )
return;
// get file name from user
fileName = fileChooser.FileName;
// show error if user specified invalid file
if ( fileName == "" || fileName == null )
MessageBox.Show( "Invalid File Name", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
// open or create file if user specified valid file
 2002 Prentice Hall.
All rights reserved.
88
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
else
{
// create Transaction with specified file
transactionProxy = new Transaction();
transactionProxy.OpenFile( fileName );
Outline
StartDialog.cs
// enable GUI buttons except for New/Open File button
newButton.Enabled = true;
updateButton.Enabled = true;
deleteButton.Enabled = true;
openButton.Enabled = false;
// instantiate dialog box for creating records
newDialog = new NewDialogForm( transactionProxy,
new MyDelegate( ShowStartDialog ) );
// instantiate dialog box for updating records
updateDialog = new UpdateDialogForm( transactionProxy,
new MyDelegate( ShowStartDialog ) );
// instantiate dialog box for removing records
deleteDialog = new DeleteDialogForm( transactionProxy,
new MyDelegate( ShowStartDialog ) );
// set StartDialog as MdiParent for dialog boxes
newDialog.MdiParent = this.MdiParent;
updateDialog.MdiParent = this.MdiParent;
deleteDialog.MdiParent = this.MdiParent;
}
} // end method openButton_Click
 2002 Prentice Hall.
All rights reserved.
89
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// invoked when user clicks New Record button
private void newButton_Click(
object sender, System.EventArgs e )
{
Hide(); // hide StartDialog
newDialog.Show(); // show NewDialog
Outline
StartDialog.cs
} // end method newButton_Click
private void updateButton_Click(
object sender, System.EventArgs e )
{
Hide(); // hide StartDialog
updateDialog.Show(); // show UpdateDialog
} // end method updateButton_Click
private void deleteButton_Click(
object sender, System.EventArgs e )
{
Hide(); // hide StartDialog
deleteDialog.Show(); // show DeleteDialog
} // end method deleteButton_Click
protected void ShowStartDialog()
{
Show();
}
} // end class StartDialogForm
 2002 Prentice Hall.
All rights reserved.
90
Outline
StartDialog.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
91
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 17.22: UpdateDialog.cs
// Enables user to update records in file.
// C#
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
Outline
UpdateDialog.cs
// Deitel namespaces
using BankLibrary;
public class UpdateDialogForm : BankUIForm
{
private System.Windows.Forms.Label transactionLabel;
private System.Windows.Forms.TextBox transactionTextBox;
private System.Windows.Forms.Button saveButton;
private System.Windows.Forms.Button cancelButton;
private System.ComponentModel.Container components = null;
// reference to object that handles transactions
private Transaction transactionProxy;
// delegate for method that displays previous window
private MyDelegate showPreviousWindow;
 2002 Prentice Hall.
All rights reserved.
92
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// initialize components and set members to parameter values
public UpdateDialogForm(
Transaction transactionProxyValue,
MyDelegate delegateValue )
{
InitializeComponent();
showPreviousWindow = delegateValue;
Outline
UpdateDialog.cs
// instantiate object that handles transactions
transactionProxy = transactionProxyValue;
}
// Visual Studio .NET generated code
// invoked when user enters text in account TextBox
private void accountTextBox_KeyDown(
object sender, System.Windows.Forms.KeyEventArgs e )
{
// determine whether user pressed Enter key
if ( e.KeyCode == Keys.Enter )
{
// retrieve record associated with account from file
RandomAccessRecord record =
transactionProxy.GetRecord( GetTextBoxValues()
[ ( int )TextBoxIndices.ACCOUNT ] );
// return if record does not exist
if ( record == null )
return;
 2002 Prentice Hall.
All rights reserved.
93
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// determine whether record is empty
if ( record.Account != 0 )
{
// store record values in string array
string[] values = {
record.Account.ToString(),
record.FirstName.ToString(),
record.LastName.ToString(),
record.Balance.ToString() };
Outline
UpdateDialog.cs
// copy string array value to TextBox values
SetTextBoxValues( values );
transactionTextBox.Text = "[Charge or Payment]";
}
else
{
// notify user if record does not exist
MessageBox.Show(
"Record Does Not Exist", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
} // end method accountTextBox_KeyDown
// invoked when user enters text in transaction TextBox
private void transactionTextBox_KeyDown(
object sender, System.Windows.Forms.KeyEventArgs e )
{
// determine whether user pressed Enter key
if ( e.KeyCode == Keys.Enter )
{
 2002 Prentice Hall.
All rights reserved.
94
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// calculate balance using transaction TextBox value
try
{
// retrieve record associated with account from file
RandomAccessRecord record =
transactionProxy.GetRecord( GetTextBoxValues()
[ ( int )TextBoxIndices.ACCOUNT ] );
Outline
UpdateDialog.cs
// get transaction TextBox value
double transactionValue =
Double.Parse( transactionTextBox.Text );
// calculate new balance (old balance + transaction)
double newBalance =
record.Balance + transactionValue;
// store record values in string array
string[] values = {
record.Account.ToString(),
record.FirstName.ToString(),
record.LastName.ToString(),
newBalance.ToString() };
// copy string array value to TextBox values
SetTextBoxValues( values );
// clear transaction TextBox
transactionTextBox.Text = "";
}
 2002 Prentice Hall.
All rights reserved.
95
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
// notify user if error occurs in parameter mismatch
catch( FormatException )
{
MessageBox.Show(
"Invalid Transaction", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Outline
UpdateDialog.cs
}
} // end method transactionTextBox_KeyDown
// invoked when user clicks Save button
private void saveButton_Click(
object sender, System.EventArgs e )
{
RandomAccessRecord record =
transactionProxy.GetRecord( GetTextBoxValues()
[ ( int )TextBoxIndices.ACCOUNT ] );
// if record exists, update in file
if ( record != null )
UpdateRecord( record );
Hide();
ClearTextBoxes();
showPreviousWindow();
} // end method saveButton_Click
 2002 Prentice Hall.
All rights reserved.
96
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// invoked when user clicks Cancel button
private void cancelButton_Click(
object sender, System.EventArgs e )
{
Hide();
ClearTextBoxes();
showPreviousWindow();
Outline
UpdateDialog.cs
} // end method cancelButton_Click
// update record in file at position specified by accountNumber
public void UpdateRecord( RandomAccessRecord record )
{
// store TextBox values in record and write record to file
try
{
int accountNumber = record.Account;
string[] values = GetTextBoxValues();
// store values in record
record.Account = accountNumber;
record.FirstName =
values[ ( int )TextBoxIndices.FIRST ];
record.LastName =
values[ ( int )TextBoxIndices.LAST ];
record.Balance =
Double.Parse(
values[ ( int )TextBoxIndices.BALANCE ] );
// add record to file
if ( transactionProxy.AddRecord(
record, accountNumber ) == false )
return; // if error
}
 2002 Prentice Hall.
All rights reserved.
97
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// notify user if error occurs in parameter mismatch
catch( FormatException )
{
MessageBox.Show( "Invalid Balance", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
Outline
UpdateDialog.cs
return;
}
MessageBox.Show( "Record Updated", "Success",
MessageBoxButtons.OK,
MessageBoxIcon.Information );
} // end method UpdateRecord
} // end class UpdateDialogForm
Program Output
 2002 Prentice Hall.
All rights reserved.
98
Outline
UpdateDialog.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Fig. 17.21: NewDialog.cs
// Enables user to insert new record into file.
// C#
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
Outline
NewDialog.cs
// Deitel namespaces
using BankLibrary;
public class NewDialogForm : BankUIForm
{
private System.Windows.Forms.Button saveButton;
private System.Windows.Forms.Button cancelButton;
private System.ComponentModel.Container components = null;
// reference to object that handles transactions
private Transaction transactionProxy;
// delegate for method that displays previous window
public MyDelegate showPreviousWindow;
// constructor
public NewDialogForm( Transaction transactionProxyValue,
MyDelegate delegateValue )
{
InitializeComponent();
showPreviousWindow = delegateValue;
 2002 Prentice Hall.
All rights reserved.
100
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// instantiate object that handles transactions
transactionProxy = transactionProxyValue;
Outline
}
// Visual Studio .NET generated code
NewDialog.cs
// invoked when user clicks Cancel button
private void cancelButton_Click(
object sender, System.EventArgs e )
{
Hide();
ClearTextBoxes();
showPreviousWindow();
} // end method cancelButton_Click
// invoked when user clicks Save As button
private void saveButton_Click(
object sender, System.EventArgs e )
{
RandomAccessRecord record =
transactionProxy.GetRecord( GetTextBoxValues()
[ ( int )TextBoxIndices.ACCOUNT ] );
// if record exists, add it to file
if ( record != null )
InsertRecord( record );
Hide();
ClearTextBoxes();
showPreviousWindow();
} // end method saveButton_Click
 2002 Prentice Hall.
All rights reserved.
101
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// insert record in file at position specified by accountNumber
private void InsertRecord( RandomAccessRecord record )
{
//store TextBox values in string array
string[] textBoxValues = GetTextBoxValues();
Outline
NewDialog.cs
// store TextBox account field
int accountNumber = Int32.Parse(
textBoxValues[ ( int )TextBoxIndices.ACCOUNT ] );
// notify user and return if record account is not empty
if ( record.Account != 0 )
{
MessageBox.Show(
"Record Already Exists or Invalid Number", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// store values in record
record.Account = accountNumber;
record.FirstName =
textBoxValues[ ( int )TextBoxIndices.FIRST];
record.LastName =
textBoxValues[ ( int )TextBoxIndices.LAST];
record.Balance = Double.Parse(
textBoxValues[ ( int )TextBoxIndices.BALANCE ] );
// add record to file
try
{
if ( transactionProxy.AddRecord(
record, accountNumber ) == false )
 2002 Prentice Hall.
All rights reserved.
102
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
return; // if error
Outline
}
// notify user if error occurs in parameter mismatch
catch( FormatException )
{
MessageBox.Show( "Invalid Balance", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
NewDialog.cs
MessageBox.Show( "Record Created", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end method InsertRecord
} // end class NewDialogForm
Program Output
 2002 Prentice Hall.
All rights reserved.
103
Outline
NewDialog.cs
Program Output
 2002 Prentice Hall.
All rights reserved.
104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Fig. 17.23: DeleteDialog.cs
// Enables user to delete records in file.
// C#
using
using
using
using
using
namespaces
System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
Outline
DeleteDialog.cs
// Deitel namespaces
using BankLibrary;
public class DeleteDialogForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label accountLabel;
private System.Windows.Forms.TextBox accountTextBox;
private System.Windows.Forms.Button deleteButton;
private System.Windows.Forms.Button cancelButton;
private System.ComponentModel.Container components = null;
// reference to object that handles transactions
private Transaction transactionProxy;
// delegate for method that displays previous window
private MyDelegate showPreviousWindow;
// initialize components and set members to parameter values
public DeleteDialogForm( Transaction transactionProxyValue,
MyDelegate delegateValue)
{
InitializeComponent();
showPreviousWindow = delegateValue;
 2002 Prentice Hall.
All rights reserved.
105
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// instantiate object that handles transactions
transactionProxy = transactionProxyValue;
}
Outline
DeleteDialog.cs
// Visual Studio .NET generated code
// invoked when user clicks Delete Record button
private void deleteButton_Click(
object sender, System.EventArgs e)
{
RandomAccessRecord record =
transactionProxy.GetRecord( accountTextBox.Text );
// if record exists, delete it in file
if ( record != null )
DeleteRecord( record );
this.Hide();
showPreviousWindow();
} // end method deleteButton_Click
// invoked when user clicks Cancel button
private void cancelButton_Click(
object sender, System.EventArgs e)
{
this.Hide();
showPreviousWindow();
} // end method cancelButton_Click
 2002 Prentice Hall.
All rights reserved.
106
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// delete record in file at position specified by accountNumber
public void DeleteRecord( RandomAccessRecord record )
{
int accountNumber = record.Account;
Outline
DeleteDialog.cs
// display error message if record does not exist
if ( record.Account == 0 )
{
MessageBox.Show( "Record Does Not Exist", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
accountTextBox.Clear();
return;
}
// create blank record
record = new RandomAccessRecord();
// write over file record with empty record
if ( transactionProxy.AddRecord(
record, accountNumber ) == true )
// notify user of successful deletion
MessageBox.Show( "Record Deleted", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information );
 2002 Prentice Hall.
All rights reserved.
107
93
94
95
96
97
98
99
100
101
102
103
104
else
// notify user of failure
MessageBox.Show(
"Record could not be deleted", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error );
Outline
DeleteDialog.cs
accountTextBox.Clear();
} // end method DeleteRecord
} // end class DeleteDialogForm
Program Output
 2002 Prentice Hall.
All rights reserved.