Upload
charlotte-cooper
View
218
Download
0
Embed Size (px)
Citation preview
1
2006 Pearson Education, Inc. All rights reserved.
1818
Files and Streams
2
2006 Pearson Education, Inc. All rights reserved.
I can only assume that a “Do Not File” document is filed in a “Do Not File” file.
— Senator Frank Church
Senate Intelligence
Subcommittee Hearing, 1975
Consciousness ... does not appear to itself chopped up in bits. ... A “river” or a “stream” are the metaphors by which it is most naturally described.
— William James
I read part of it all the way through.— Samuel Goldwyn
3
2006 Pearson Education, Inc. All rights reserved.
OBJECTIVESIn this chapter you will learn: To create, read, write and update files. The C# streams class hierarchy. To use classes File and Directory to obtain
information about files and directories on your computer.
To become familiar with sequential-access file processing.
To use classes FileStream, StreamReader and StreamWriter to read text from and write text to files.
To use classes FileStream and BinaryFormatter to read objects from and write objects to files.
4
2006 Pearson Education, Inc. All rights reserved.
18.1 Introduction
18.2 Data Hierarchy
18.3 Files and Streams
18.4 Classes File and Directory
18.5 Creating a Sequential-Access Text File
18.6 Reading Data from a Sequential-Access Text File
18.7 Serialization
18.8 Creating a Sequential-Access File Using Object Serialization
18.9 Reading and Deserializing Data from a Sequential-Access Text File
18.10 Wrap-Up
5
2006 Pearson Education, Inc. All rights reserved.
18.1 Introduction
• Persistent Data– Data maintained in files
• Create, upload and process data files in C#
• Overview of data hierarchy
• Overview of FCL’s file-processing classes
6
2006 Pearson Education, Inc. All rights reserved.
18.2 Data Hierarchy
• Data Hierarchy– All data in computers are combinations of 0s and 1s– The smallest data item is called a bit (Contains 0 or 1)– Bytes are composed of eight bits
• C# uses the Unicode® character set in which characters are composed of 2 bytes
– Characters are composed of bits– A field is a group of characters– A record/file is composed of several related fields– A group of related files often are stored in a database
• A collection of programs designed to create and manage databases is called a database management system (DBMS)
7
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.1 | Data hierarchy.
8
2006 Pearson Education, Inc. All rights reserved.
18.3 Files and Streams
• Files and Streams– C# views each file as a sequential stream of bytes
• Each file ends either with:– An end-of-file marker – Specific byte number
• Recorded in a system-maintained administrative data structure
– An object is created and a stream is associated with the object when a file is opened
– The runtime environment creates three stream objects: • Console.In (Refers to the standard input stream object)
– Enables a program to input data from the keyboard• Console.Out (Refers to the standard output stream object)
– Enables a program to output data to the screen• Console.Error (Refers to the standard error stream object)
– Enables a program to output error messages to the screen
9
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.2 | C#’s view of an n-byte file.
10
2006 Pearson Education, Inc. All rights reserved.
18.3 Files and Streams (Cont.)• There are many file-processing classes in the FCL (Framework Class
Library)– Class StreamReader
• For text input from a file• Inherits from abstract class TextReader
– Class StreamWriter• For text output to a file• Inherits from abstract class TextWriter
– Class FileStream • For both input from and output to a file• Can be used to write data to and read data from files • Inherits from abstract class Stream
– Class MemoryStream • Enables the transfer of data directly to and from memory
– Class BufferedStream • Uses buffering to transfer data to or from a stream
– Properties of Console.In and Console.Out are of type TextReader and TextWriter, respectively
11
2006 Pearson Education, Inc. All rights reserved.
18.3 Files and Streams (Cont.)
• Buffering– An I/O performance-enhancement technique
– Each output operation is directed to a buffer • Aka region in memory
– Output is performed more efficiently • Large physical output operation each time the buffer fills
– Less overhead
– Used to speed input operations • Reading more data than is required into a buffer
• Subsequent reads get data from memory rather than external device
12
2006 Pearson Education, Inc. All rights reserved.
18.4 Classes File and Directory
• Classes File and Directory – Enable programs to manipulate files and directories on disk
– Class File • Determine information about files and can be used to open files for
reading or writing
– Class Directory • Provides capabilities for manipulating directories
• CreateDirectory method
– Returns DirectoryInfo object
• Contain information about a directory
13
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.3 | File class static methods (partial list). (Part 1 of 2.)
static Method Description
AppendText Returns a StreamWriter that appends text 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.
Exists Returns true if the specified file exists and false otherwise.
GetCreationTime Returns a DateTime object representing when the file was created.
GetLastAccessTime Returns a DateTime object representing when the file was last accessed.
14
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.3 | File class static methods (partial list). (Part 2 of 2.)
static Method Description
GetLastWriteTime Returns a DateTime object representing when 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.
OpenText Returns a StreamReader associated with the specified file.
OpenWrite Returns a read/write FileStream associated with the specified file.
15
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.4 | Directory class static methods.
static Method Description
CreateDirectory Creates a directory and returns its associated DirectoryInfo object.
Delete Deletes the specified directory.
Exists Returns true if the specified directory exists and false otherwise.
GetDirectories Returns a string array containing the names of the subdirectories in the specified directory.
GetFiles Returns a string array containing the names of the files in the specified directory.
GetCreationTime Returns a DateTime object representing when the directory was created.
GetLastAccessTime Returns a DateTime object representing when the directory was last accessed.
GetLastWriteTime Returns a DateTime object representing when items were last written to the directory.
Move Moves the specified directory to a specified location.
16
2006 Pearson Education, Inc. All rights reserved.
1 // Fig 18.5: FileTestForm.cs
2 // Using classes File and Directory.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6
7 // displays contents of files and directories
8 public partial class FileTestForm : Form
9 {
10 // parameterless constructor
11 public FileTestForm()
12 {
13 InitializeComponent();
14 } // end constructor
15
16 // invoked when user presses key
17 private void inputTextBox_KeyDown( object sender, KeyEventArgs e )
18 {
19 // determine whether user pressed Enter key
20 if ( e.KeyCode == Keys.Enter )
21 {
22 string fileName; // name of file or directory
23
24 // get user-specified file or directory
25 fileName = inputTextBox.Text;
Outline
FileTestForm.cs
(1 of 5)
17
2006 Pearson Education, Inc. All rights reserved.
26
27 // determine whether fileName is a file
28 if ( File.Exists( fileName ) )
29 {
30 // get file's creation date,
31 // modification date, etc.
32 outputTextBox.Text = GetInformation( fileName );
33
34 // display file contents through StreamReader
35 try
36 {
37 // obtain reader and file contents
38 StreamReader stream = new StreamReader( fileName );
39 outputTextBox.Text += stream.ReadToEnd();
40 } // end try
41 // handle exception if StreamReader is unavailable
42 catch ( IOException )
43 {
44 MessageBox.Show( "Error reading from file", "File Error",
45 MessageBoxButtons.OK, MessageBoxIcon.Error );
46 } // end catch
47 } // end if
48 // determine whether fileName is a directory
49 else if ( Directory.Exists( fileName ) )
50 {
51 string[] directoryList; // array for directories
52
53 // get directory's creation date,
54 // modification date, etc.
55 outputTextBox.Text = GetInformation( fileName );
Outline
FileTestForm.cs
(2 of 5)
Checks to see if filename is an existing file
Instantiates a StreamReader for reading text from a file
Checks to see if filename is an existing directory
18
2006 Pearson Education, Inc. All rights reserved.
56
57 // obtain file/directory list of specified directory
58 directoryList = Directory.GetDirectories( fileName );
59
60 outputTextBox.Text += "\r\n\r\nDirectory contents:\r\n";
61
62 // output directoryList contents
63 for ( int i = 0; i < directoryList.Length; i++ )
64 outputTextBox.Text += directoryList[ i ] + "\r\n";
65 } // end else if
66 else
67 {
68 // notify user that neither file nor directory exists
69 MessageBox.Show( inputTextBox.Text +
70 " does not exist", "File Error",
71 MessageBoxButtons.OK, MessageBoxIcon.Error );
72 } // end else
73 } // end if
74 } // end method inputTextBox_KeyDown
75
76 // get information on file or directory
77 private string GetInformation( string fileName )
78 {
79 string information;
80
81 // output that file or directory exists
82 information = fileName + " exists\r\n\r\n";
Outline
FileTestForm.cs
(3 of 5)Obtain a string array containing the names of the subdirectories in
the specified directory
If successful, output results
If not, notify user
19
2006 Pearson Education, Inc. All rights reserved.
83
84 // output when file or directory was created
85 information += "Created: " +
86 File.GetCreationTime( fileName ) + "\r\n";
87
88 // output when file or directory was last modified
89 information += "Last modified: " +
90 File.GetLastWriteTime( fileName ) + "\r\n";
91
92 // output when file or directory was last accessed
93 information += "Last accessed: " +
94 File.GetLastAccessTime( fileName ) + "\r\n" + "\r\n";
95
96 return information;
97 } // end method GetInformation
98 } // end class FileTestForm
Outline
FileTestForm.cs
(4 of 5)
(a) (b)
Returns a DateTime object representing when the file
was created
Returns a DateTime object representing when the file
was last modified
Returns a DateTime object representing when the file
was last accessed
20
2006 Pearson Education, Inc. All rights reserved.
Outline
FileTestForm.cs
(5 of 5)
(c) (d)
21
2006 Pearson Education, Inc. All rights reserved.
1 // Fig 18.6: FileSearchForm.cs
2 // Using regular expressions to determine file types.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6 using System.Text.RegularExpressions;
7 using System.Collections.Specialized;
8
9 // uses regular expressions to determine file types
10 public partial class FileSearchForm : Form
11 {
12 string currentDirectory = Directory.GetCurrentDirectory();
13 string[] directoryList; // subdirectories
14 string[] fileArray;
15
16 // store extensions found and number found
17 NameValueCollection found = new NameValueCollection();
18
19 // parameterless constructor
20 public FileSearchForm()
21 {
22 InitializeComponent();
23 } // end constructor
24
Outline
FileSearchForm.cs
(1 of 6)
Returns the current project’s directory
Create an object of NameValueCollection
22
2006 Pearson Education, Inc. All rights reserved.
25 // invoked when user types in text box
26 private void inputTextBox_KeyDown( object sender, KeyEventArgs e )
27 {
28 // determine whether user pressed Enter
29 if ( e.KeyCode == Keys.Enter )
30 searchButton_Click( sender, e );
31 } // end method inputTextBox_KeyDown
32
33 // invoked when user clicks "Search Directory" button
34 private void searchButton_Click( object sender, EventArgs e )
35 {
36 // check for user input; default is current directory
37 if ( inputTextBox.Text != "" )
38 {
39 // verify that user input is valid directory name
40 if ( Directory.Exists( inputTextBox.Text ) )
41 {
42 currentDirectory = inputTextBox.Text;
43
44 // reset input text box and update display
45 directoryLabel.Text = "Current Directory:" +
46 "\r\n" + currentDirectory;
47 } // end if
48 else
49 {
50 // show error if user does not specify valid directory
51 MessageBox.Show( "Invalid Directory", "Error",
52 MessageBoxButtons.OK, MessageBoxIcon.Error );
53 } // end else
54 } // end if
Outline
FileSearchForm.cs
(2 of 6)
Determine if inputTextBox.Text is
an existing directory
23
2006 Pearson Education, Inc. All rights reserved.
55
56 // clear text boxes
57 inputTextBox.Text = "";
58 outputTextBox.Text = "";
59
60 SearchDirectory( currentDirectory ); // search directory
61
62 // summarize and print results
63 foreach ( string current in found )
64 {
65 outputTextBox.Text += "* Found " +
66 found[ current ] + " " + current + " files.\r\n";
67 } // end foreach
68
69 // clear output for new search
70 found.Clear();
71 } // end method searchButton_Click
72
73 // search directory using regular expression
74 private void SearchDirectory( string currentDirectory )
75 {
76 // for file name without directory path
77 try
78 {
79 string fileName = "";
80
81 // regular expression for extensions matching pattern
82 Regex regularExpression = new Regex(
83 @"[a-zA-Z0-9]+\.(?<extension>\w+)" );
Outline
FileSearchForm.cs
(3 of 6)
Use key string to access corresponding value
Reset for the next search
Matches any sequence of numbers or letters followed by a period
and one or more letters
24
2006 Pearson Education, Inc. All rights reserved.
84
85 // stores regular-expression match result
86 Match matchResult;
87
88 string fileExtension; // holds file extensions
89
90 // number of files with given extension in directory
91 int extensionCount;
92
93 // get directories
94 directoryList = Directory.GetDirectories( currentDirectory );
95
96 // get list of files in current directory
97 fileArray = Directory.GetFiles( currentDirectory );
98
99 // iterate through list of files
100 foreach ( string myFile in fileArray )
101 {
102 // remove directory path from file name
103 fileName = myFile.Substring( myFile.LastIndexOf( @"\" ) + 1 );
104
105 // obtain result for regular-expression search
106 matchResult = regularExpression.Match( fileName );
107
108 // check for match
109 if ( matchResult.Success )
110 fileExtension = matchResult.Result( "${extension}" );
111 else
112 fileExtension = "[no extension]";
113
Outline
FileSearchForm.cs
(4 of 6)Retrieve the names of all subdirectories that belong to
the current directory
Store the names of files in the current directory
Eliminate the directory path
Return the matches for the regular expression
25
2006 Pearson Education, Inc. All rights reserved.
114 // store value from container
115 if ( found[ fileExtension ] == null )
116 found.Add( fileExtension, "1" );
117 else
118 {
119 extensionCount = Int32.Parse( found[ fileExtension ] ) + 1;
120 found[ fileExtension ] = extensionCount.ToString();
121 } // end else
122
123 // search for backup( .bak ) files
124 if ( fileExtension == "bak" )
125 {
126 // prompt user to delete ( .bak ) file
127 DialogResult result =
128 MessageBox.Show( "Found backup file " +
129 fileName + ". Delete?", "Delete Backup",
130 MessageBoxButtons.YesNo, MessageBoxIcon.Question );
131
132 // delete file if user clicked 'yes'
133 if ( result == DialogResult.Yes )
134 {
135 File.Delete( myFile );
136 extensionCount = Int32.Parse( found[ "bak" ] ) - 1;
137 found[ "bak" ] = extensionCount.ToString();
138 } // end if
139 } // end if
140 } // end foreach
Outline
FileSearchForm.cs
(5 of 6)
Determine if this is the first occurrence of the filename extension
If not, increment the value associated with the extension
Delete the file and decrement the corresponding value
26
2006 Pearson Education, Inc. All rights reserved.
141
142 // recursive call to search files in subdirectory
143 foreach ( string myDirectory in directoryList )
144 SearchDirectory( myDirectory );
145 } // end try
146 // handle exception if files have unauthorized access
147 catch ( UnauthorizedAccessException )
148 {
149 MessageBox.Show( "Some files may not be visible" +
150 " due to permission settings", "Warning",
151 MessageBoxButtons.OK, MessageBoxIcon.Information );
152 } // end catch
153 } // end method SearchDirectory
154 } // end class FileSearchForm
Outline
FileSearchForm.cs
(6 of 6)
Notify user of any unauthorized file access
27
2006 Pearson Education, Inc. All rights reserved.
18.5 Creating a Sequential-Access Text File
• C# imposes no structure on files– The concept of a “record” does not exist in C# files
• Must structure files to meet the requirements of your applications
• Class FileStream – Objects can open files to perform text manipulation
• Class StreamWriter– Objects is constructed with a FileStream argument
• Specifies the file to output text
28
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.7: BankUIForm.cs
2 // A reusable Windows Form for the examples in this chapter.
3 using System;
4 using System.Windows.Forms;
5
6 public partial class BankUIForm : Form
7 {
8 protected int TextBoxCount = 4; // number of TextBoxes on Form
9
10 // enumeration constants specify TextBox indices
11 public enum TextBoxIndices
12 {
13 ACCOUNT,
14 FIRST,
15 LAST,
16 BALANCE
17 } // end enum
18
19 // parameterless constructor
20 public BankUIForm()
21 {
22 InitializeComponent();
23 } // end constructor
Outline
BankUIForm.cs
(1 of 4)
Define enumeration for the textbox’s indices
29
2006 Pearson Education, Inc. All rights reserved.
24
25 // clear all TextBoxes
26 public void ClearTextBoxes()
27 {
28 // iterate through every Control on form
29 for ( int i = 0; i < Controls.Count; i++ )
30 {
31 Control myControl = Controls[ i ]; // get control
32
33 // determine whether Control is TextBox
34 if ( myControl is TextBox )
35 {
36 // clear Text property ( set to empty string )
37 myControl.Text = "";
38 } // end if
39 } // end for
40 } // end method ClearTextBoxes
Outline
BankUIForm.cs
(2 of 4)
Clear textbox
30
2006 Pearson Education, Inc. All rights reserved.
41
42 // set text box values to string array values
43 public void SetTextBoxValues( string[] values )
44 {
45 // determine whether string array has correct length
46 if ( values.Length != TextBoxCount )
47 {
48 // throw exception if not correct length
49 throw( new ArgumentException( "There must be " +
50 ( TextBoxCount + 1 ) + " strings in the array" ) );
51 } // end if
52 // set array values if array has correct length
53 else
54 {
55 // set array values to text box values
56 accountTextBox.Text = values[ ( int ) TextBoxIndices.ACCOUNT ];
57 firstNameTextBox.Text = values[ ( int ) TextBoxIndices.FIRST ];
58 lastNameTextBox.Text = values[ ( int ) TextBoxIndices.LAST ];
59 balanceTextBox.Text = values[ ( int ) TextBoxIndices.BALANCE ];
60 } // end else
61 } // end method SetTextBoxValues
Outline
BankUIForm.cs
(3 of 4)
Set textboxes to corresponding values
31
2006 Pearson Education, Inc. All rights reserved.
62
63 // return text box values as string array
64 public string[] GetTextBoxValues()
65 {
66 string[] values = new string[ TextBoxCount ];
67
68 // copy text box fields to string array
69 values[ ( int ) TextBoxIndices.ACCOUNT ] = accountTextBox.Text;
70 values[ ( int ) TextBoxIndices.FIRST ] = firstNameTextBox.Text;
71 values[ ( int ) TextBoxIndices.LAST ] = lastNameTextBox.Text;
72 values[ ( int ) TextBoxIndices.BALANCE ] = balanceTextBox.Text;
73
74 return values;
75 } // end method GetTextBoxValues
76 } // end class BankUIForm
Outline
BankUIForm.cs
(4 of 4)
Return textboxes’ values
32
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.8: Record.cs
2 // Serializable class that represents a data record.
3 using System;
4 using System.Collections.Generic;
5 using System.Text;
6
7 public class Record
8 {
9 private int account;
10 private string firstName;
11 private string lastName;
12 private decimal balance;
13
14 // parameterless constructor sets members to default values
15 public Record() : this( 0, "", "", 0.0M )
16 {
17 } // end constructor
18
19 // overloaded constructor sets members to parameter values
20 public Record( int accountValue, string firstNameValue,
21 string lastNameValue, decimal balanceValue )
22 {
23 Account = accountValue;
24 FirstName = firstNameValue;
25 LastName = lastNameValue;
26 Balance = balanceValue;
27 } // end constructor
Outline
Record.cs
(1 of 3)private instance values representing all the information for a record
Initializes the private instance variables’ value
33
2006 Pearson Education, Inc. All rights reserved.
28
29 // property that gets and sets Account
30 public int Account
31 {
32 get
33 {
34 return account;
35 } // end get
36 set
37 {
38 account = value;
39 } // end set
40 } // end property Account
41
42 // property that gets and sets FirstName
43 public string FirstName
44 {
45 get
46 {
47 return firstName;
48 } // end get
49 set
50 {
51 firstName = value;
52 } // end set
53 } // end property FirstName
Outline
Record.cs
(2 of 3)
Property for private instance variable account
Property for private instance variable firstName
34
2006 Pearson Education, Inc. All rights reserved.
54
55 // property that gets and sets LastName
56 public string LastName
57 {
58 get
59 {
60 return lastName;
61 } // end get
62 set
63 {
64 lastName = value;
65 } // end set
66 } // end property LastName
67
68 // property that gets and sets Balance
69 public decimal Balance
70 {
71 get
72 {
73 return balance;
74 } // end get
75 set
76 {
77 balance = value;
78 } // end set
79 } // end property Balance
80 } // end class Record
Outline
Record.cs
(3 of 3)
Property for private instance variable lastName
Property for private instance variable balance
35
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.9: CreateFileForm.cs
2 // Creating a sequential-access file.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6 using BankLibrary;
7
8 public partial class CreateFileForm : BankUIForm
9 {
10 private StreamWriter fileWriter; // writes data to text file
11 private FileStream output; // maintains connection to file
12
13 // parameterless constructor
14 public CreateFileForm()
15 {
16 InitializeComponent();
17 } // end constructor
18
19 // event handler for Save Button
20 private void saveButton_Click( object sender, EventArgs e )
21 {
22 // create dialog box enabling user to save file
23 SaveFileDialog fileChooser = new SaveFileDialog();
24 DialogResult result = fileChooser.ShowDialog();
25 string fileName; // name of file to save data
26
27 fileChooser.CheckFileExists = false; // allow user to create file
Outline
CreateFileForm.cs
(1 of 8)
Create a StreamWriter object for writing text to a file
Create a FileStream object for connecting to a file
Prompt user for location to save file
Do not notify user that file does not exist
36
2006 Pearson Education, Inc. All rights reserved.
28
29 // exit event handler if user clicked "Cancel"
30 if ( result == DialogResult.Cancel )
31 return;
32
33 fileName = fileChooser.FileName; // get specified file name
34
35 // show error if user specified invalid file
36 if ( fileName == "" || fileName == null )
37 MessageBox.Show( "Invalid File Name", "Error",
38 MessageBoxButtons.OK, MessageBoxIcon.Error );
39 else
40 {
41 // save file via FileStream if user specified valid file
42 try
43 {
44 // open file with write access
45 output = new FileStream( fileName,
46 FileMode.OpenOrCreate, FileAccess.Write );
47
48 // sets file to where data is written
49 fileWriter = new StreamWriter( output );
50
51 // disable Save button and enable Enter button
52 saveButton.Enabled = false;
53 enterButton.Enabled = true;
54 } // end try
Outline
CreateFileForm.cs
(2 of 8)Obtain user-selected file
Open the file if the file exists or create the file if it does not exist
Indicates that the program can perform only write operations with this object
Instantiate the StreamWriter object to write text to a file
37
2006 Pearson Education, Inc. All rights reserved.
55 // handle exception if there is a problem opening the file
56 catch ( IOException )
57 {
58 // notify user if file does not exist
59 MessageBox.Show( "Error opening file", "Error",
60 MessageBoxButtons.OK, MessageBoxIcon.Error );
61 } // end catch
62 } // end else
63 } // end method saveButton_Click
64
65 // handler for enterButton Click
66 private void enterButton_Click( object sender, EventArgs e )
67 {
68 // store TextBox values string array
69 string[] values = GetTextBoxValues();
70
71 // Record containing TextBox values to serialize
72 Record record = new Record();
73
74 // determine whether TextBox account field is empty
75 if ( values[ ( int ) TextBoxIndices.ACCOUNT ] != "" )
76 {
77 // store TextBox values in Record and serialize Record
78 try
79 {
80 // get account number value from TextBox
81 int accountNumber = Int32.Parse(
82 values[ ( int ) TextBoxIndices.ACCOUNT ] );
Outline
CreateFileForm.cs
(3 of 8)
Create a Record object to hold textboxes’ data
38
2006 Pearson Education, Inc. All rights reserved.
83
84 // determine whether accountNumber is valid
85 if ( accountNumber > 0 )
86 {
87 // store TextBox fields in Record
88 record.Account = accountNumber;
89 record.FirstName = values[ ( int ) TextBoxIndices.FIRST ];
90 record.LastName = values[ ( int ) TextBoxIndices.LAST ];
91 record.Balance = Decimal.Parse(
92 values[ ( int ) TextBoxIndices.BALANCE ] );
93
94 // write Record to file, fields separated by commas
95 fileWriter.WriteLine(
96 record.Account + "," + record.FirstName + "," +
97 record.LastName + "," + record.Balance );
98 } // end if
99 else
100 {
101 // notify user if invalid account number
102 MessageBox.Show( "Invalid Account Number", "Error",
103 MessageBoxButtons.OK, MessageBoxIcon.Error );
104 } // end else
105 } // end try
106 // notify user if error occurs in serialization
107 catch ( IOException )
108 {
109 MessageBox.Show( "Error Writing to File", "Error",
110 MessageBoxButtons.OK, MessageBoxIcon.Error );
111 } // end catch
Outline
CreateFileForm.cs
(4 of 8)
Store and write record information
39
2006 Pearson Education, Inc. All rights reserved.
112 // notify user if error occurs regarding parameter format
113 catch ( FormatException )
114 {
115 MessageBox.Show( "Invalid Format", "Error",
116 MessageBoxButtons.OK, MessageBoxIcon.Error );
117 } // end catch
118 } // end if
119
120 ClearTextBoxes(); // clear TextBox values
121 } // end method enterButton_Click
122
123 // handler for exitButton Click
124 private void exitButton_Click( object sender, EventArgs e )
125 {
126 // determine whether file exists
127 if ( output != null )
128 {
129 try
130 {
131 fileWriter.Close(); // close StreamWriter
132 output.Close(); // close file
133 } // end try
134 // notify user of error closing file
135 catch ( IOException )
136 {
137 MessageBox.Show( "Cannot close file", "Error",
138 MessageBoxButtons.OK, MessageBoxIcon.Error );
139 } // end catch
140 } // end if
Outline
CreateFileForm.cs
(5 of 8)
Release the program’s resources
40
2006 Pearson Education, Inc. All rights reserved.
141
142 Application.Exit();
143 } // end method exitButton_Click
144 } // end class CreateFileForm
Outline
CreateFileForm.cs
(6 of 8)
(a)
BankUI graphical
User interface
SaveFileDialog
Files and directories
(b)
41
2006 Pearson Education, Inc. All rights reserved.
Outline
CreateFileForm.cs
(7 of 8)
(c)
(e)
(d)
(f)
42
2006 Pearson Education, Inc. All rights reserved.
Outline
CreateFileForm.cs
(8 of 8)
(g) (h)
43
2006 Pearson Education, Inc. All rights reserved.
Good Programming Practice 18.1
When opening files, use the FileAccess enumeration to control user access to these files.
44
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 18.1
Failure to open a file before attempting to reference it in a program is a logic error.
45
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 18.1
Close each file explicitly when the program no longer needs to reference the file. This can reduce resource usage in programs that continue executing long after they finish using a specific file. The practice of explicitly closing files also improves program clarity.
46
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 18.2
Releasing resources explicitly when they are no longer needed makes them immediately available for reuse by other programs, thus improving resource utilization.
47
2006 Pearson Education, Inc. All rights reserved.
Fig. 18.10 | Sample data for the program of Fig. 18.9.
Account Number First Name Last Name Balance
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
48
2006 Pearson Education, Inc. All rights reserved.
18.6 Reading Data from a Sequential-Access Text File
• Programs normally start from the beginning of the file to retrieve data sequentially from a file
– Sometimes it is necessary to process a file sequentially several times
• FileStream object – Can reposition its file-position pointer to any position in the file
• Pointer contains the next byte to be read from or written
• Its file-position pointer is set to byte position 0 when file is opened
• Method Seek
– Reset the file-position pointer
• Specify the number of bytes it should be offset from the file’s beginning, end or current position
- The part of the file you want to be offset from is chosen using constants from the SeekOrigin enumeration
49
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.11: ReadSequentialAccessFileForm.cs
2 // Reading a sequential-access file.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6 using BankLibrary;
7
8 public partial class ReadSequentialAccessFileForm : BankUIForm
9 {
10 private FileStream input; // maintains connection to a file
11 private StreamReader fileReader; // reads data from a text file
12
13 // paramterless constructor
14 public ReadSequentialAccessFileForm()
15 {
16 InitializeComponent();
17 } // end constructor
18
19 // invoked when user clicks the Open button
20 private void openButton_Click( object sender, EventArgs e )
21 {
22 // create dialog box enabling user to open file
23 OpenFileDialog fileChooser = new OpenFileDialog();
24 DialogResult result = fileChooser.ShowDialog();
25 string fileName; // name of file containing data
26
27 // exit event handler if user clicked Cancel
28 if ( result == DialogResult.Cancel )
29 return;
Outline
ReadSequentialAccessFileForm.cs
(1 of 6)
Create a StreamReader object for reading text from a file
Create a FileStream object for connecting to a file
Prompt user for a file to read
Check to see if user pressed “Cancel”
50
2006 Pearson Education, Inc. All rights reserved.
30
31 fileName = fileChooser.FileName; // get specified file name
32 ClearTextBoxes();
33
34 // show error if user specified invalid file
35 if ( fileName == "" || fileName == null )
36 MessageBox.Show( "Invalid File Name", "Error",
37 MessageBoxButtons.OK, MessageBoxIcon.Error );
38 else
39 {
40 // create FileStream to obtain read access to file
41 input = new FileStream( fileName, FileMode.Open,
42 FileAccess.Read );
43
44 // set file from where data is read
45 fileReader = new StreamReader( input );
46
47 openButton.Enabled = false; // disable Open File button
48 nextButton.Enabled = true; // enable next record button
49 } // end else
50 } // end method openButton_Click
Outline
ReadSequentialAccessFileForm.cs
(2 of 6)Open file if exist or throw exception
Indicates that the program can perform only read operations with this object
Instantiate the StreamReader object to read text from a file
51
2006 Pearson Education, Inc. All rights reserved.
51
52 // invoked when user clicks Next button
53 private void nextButton_Click( object sender, EventArgs e )
54 {
55 try
56 {
57 // get next record available in file
58 string inputRecord = fileReader.ReadLine();
59 string[] inputFields; // will store individual pieces of data
60
61 if ( inputRecord != null )
62 {
63 inputFields = inputRecord.Split( ',' );
64
65 Record record = new Record(
66 Convert.ToInt32( inputFields[ 0 ] ), inputFields[ 1 ],
67 inputFields[ 2 ], Convert.ToDecimal( inputFields[ 3 ] ) );
68
69 // copy string array values to TextBox values
70 SetTextBoxValues( inputFields );
71 } // end if
72 else
73 {
74 fileReader.Close(); // close StreamReader
75 input.Close(); // close FileStream if no Records in file
76 openButton.Enabled = true; // enable Open File button
77 nextButton.Enabled = false; // disable Next Record button
78 ClearTextBoxes();
Outline
ReadSequentialAccessFileForm.cs
(3 of 6)
Read line of text from file
Separate stream of characters that was read from the file into strings and store results as a Record object
Release the program’s resources
52
2006 Pearson Education, Inc. All rights reserved.
79
80 // notify user if no Records in file
81 MessageBox.Show( "No more records in file", "",
82 MessageBoxButtons.OK, MessageBoxIcon.Information );
83 } // end else
84 } // end try
85 catch ( IOException )
86 {
87 MessageBox.Show( "Error Reading from File", "Error",
88 MessageBoxButtons.OK, MessageBoxIcon.Error );
89 } // end catch
90 } // end method nextButton_Click
91 } // end class readSequentialAccessFileForm
Outline
ReadSequentialAccessFileForm.cs
(4 of 6)
(a)
53
2006 Pearson Education, Inc. All rights reserved.
Outline
ReadSequentialAccessFileForm.cs
(5 of 6)
(b)
(c) (d)
54
2006 Pearson Education, Inc. All rights reserved.
Outline
ReadSequentialAccessFileForm.cs
(6 of 6)
(e)
(g) (h)
(f)
55
2006 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 18.1
Open a file with the FileAccess.Read file-open mode if the contents of the file should not be modified. This prevents unintentional modification of the contents.
56
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.12: CreditInquiryForm.cs
2 // Read a file sequentially and display contents based on
3 // account type specified by user ( credit, debit or zero balances ).
4 using System;
5 using System.Windows.Forms;
6 using System.IO;
7 using BankLibrary;
8
9 public partial class CreditInquiryForm : Form
10 {
11 private FileStream input; // maintains the connection to the file
12 private StreamReader fileReader; // reads data from text file
13
14 // name of file that stores credit, debit and zero balances
15 private string fileName;
16
17 // parameterless constructor
18 public CreditInquiryForm()
19 {
20 InitializeComponent();
21 } // end constructor
22
23 // invoked when user clicks Open File button
24 private void openButton_Click( object sender, EventArgs e )
25 {
26 // create dialog box enabling user to open file
27 OpenFileDialog fileChooser = new OpenFileDialog();
28 DialogResult result = fileChooser.ShowDialog();
Outline
CreditInquiryForm.cs
(1 of 8)
Create a StreamReader object for reading text from a file
Create a FileStream object for connecting to a file
Prompt user for the file to read
57
2006 Pearson Education, Inc. All rights reserved.
29
30 // exit event handler if user clicked Cancel
31 if ( result == DialogResult.Cancel )
32 return;
33
34 fileName = fileChooser.FileName; // get name from user
35
36 // show error if user specified invalid file
37 if ( fileName == "" || fileName == null )
38 MessageBox.Show( "Invalid File Name", "Error",
39 MessageBoxButtons.OK, MessageBoxIcon.Error );
40 else
41 {
42 // create FileStream to obtain read access to file
43 input = new FileStream( fileName,
44 FileMode.Open, FileAccess.Read );
45
46 // set file from where data is read
47 fileReader = new StreamReader( input );
48
49 // enable all GUI buttons, except for Open File button
50 openButton.Enabled = false;
51 creditButton.Enabled = true;
52 debitButton.Enabled = true;
53 zeroButton.Enabled = true;
54 } // end else
55 } // end method openButton_Click
Outline
CreditInquiryForm.cs
(2 of 8)Open file if exist or throw exception
Indicates that the program can perform only read operations with this object
Instantiate the StreamReader object to read text from a file
58
2006 Pearson Education, Inc. All rights reserved.
56
57 // invoked when user clicks credit balances,
58 // debit balances or zero balances button
59 private void getBalances_Click( object sender, System.EventArgs e )
60 {
61 // convert sender explicitly to object of type button
62 Button senderButton = ( Button )sender;
63
64 // get text from clicked Button, which stores account type
65 string accountType = senderButton.Text;
66
67 // read and display file information
68 try
69 {
70 // go back to the beginning of the file
71 input.Seek( 0, SeekOrigin.Begin );
72
73 displayTextBox.Text = "The accounts are:\r\n";
74
75 // traverse file until end of file
76 while ( true )
77 {
78 string[] inputFields; // will store individual pieces of data
79 Record record; // store each Record as file is read
80 decimal balance; // store each Record's balance
81
82 // get next Record available in file
83 string inputRecord = fileReader.ReadLine();
Outline
CreditInquiryForm.cs
(3 of 8)
Reset file-position point back to the beginning of the file
Read line of text from file
59
2006 Pearson Education, Inc. All rights reserved.
84
85 // when at the end of file, exit method
86 if ( inputRecord == null )
87 return;
88
89 inputFields = inputRecord.Split( ',' ); // parse input
90
91 // create Record from input
92 record = new Record(
93 Convert.ToInt32( inputFields[ 0 ] ), inputFields[ 1 ],
94 inputFields[ 2 ], Convert.ToDecimal( inputFields[ 3 ] ) );
95
96 // store record's last field in balance
97 balance = record.Balance;
98
99 // determine whether to display balance
100 if ( ShouldDisplay( balance, accountType ) )
101 {
102 // display record
103 string output = record.Account + "\t" +
104 record.FirstName + "\t" + record.LastName + "\t";
105
106 // display balance with correct monetary format
107 output += string.Format( "{0:F}", balance ) + "\r\n";
108
109 displayTextBox.Text += output; // copy output to screen
110 } // end if
111 } // end while
112 } // end try
113 // handle exception when file cannot be read
Outline
CreditInquiryForm.cs
(4 of 8)
Separate stream of characters that was read from the file into strings and store results as a Record object
60
2006 Pearson Education, Inc. All rights reserved.
114 catch ( IOException )
115 {
116 MessageBox.Show( "Cannot Read File", "Error",
117 MessageBoxButtons.OK, MessageBoxIcon.Error );
118 } // end catch
119 } // end method getBalances_Click
120
121 // determine whether to display given record
122 private bool ShouldDisplay( decimal balance, string accountType )
123 {
124 if ( balance > 0 )
125 {
126 // display credit balances
127 if ( accountType == "Credit Balances" )
128 return true;
129 } // end if
130 else if ( balance < 0 )
131 {
132 // display debit balances
133 if ( accountType == "Debit Balances" )
134 return true;
135 } // end else if
136 else // balance == 0
137 {
138 // display zero balances
139 if ( accountType == "Zero Balances" )
140 return true;
141 } // end else
Outline
CreditInquiryForm.cs
(5 of 8)
61
2006 Pearson Education, Inc. All rights reserved.
142
143 return false;
144 } // end method ShouldDisplay
145
146 // invoked when user clicks Done button
147 private void doneButton_Click( object sender, EventArgs e )
148 {
149 // determine whether file exists
150 if ( input != null )
151 {
152 // close file and StreamReader
153 try
154 {
155 input.Close();
156 fileReader.Close();
157 } // end try
158 // handle exception if FileStream does not exist
159 catch( IOException )
160 {
161 // notify user of error closing file
162 MessageBox.Show( "Cannot close file", "Error",
163 MessageBoxButtons.OK, MessageBoxIcon.Error );
164 } // end catch
165 } // end if
166
167 Application.Exit();
168 } // end method doneButton_Click
169 } // end class CreditInquiryForm
Outline
CreditInquiryForm.cs
(6 of 8)
Release the program’s resources
62
2006 Pearson Education, Inc. All rights reserved.
Outline
CreditInquiryForm.cs
(7 of 8)
(a)
(b)
63
2006 Pearson Education, Inc. All rights reserved.
Outline
CreditInquiryForm.cs
(8 of 8)
(c)
(d)
(e)
64
2006 Pearson Education, Inc. All rights reserved.
18.7 Serialization• Object serialization
– A serialized object is as a sequence of bytes that includes the object’s: • Data• Type • The types of data stored in the object
– Serialization can transmit objects between applications over a network– Serialized object can be read from the file
• Object Deserialization– The type information and bytes that represent the object and its data can be used to
recreate the object in memory
• Class BinaryFormatter – Enables entire objects to be written to or read from a stream– Method Serialize
• Writes an object’s representation to a file– Method Deserialize
• Reads this representation from a file and reconstructs the original object– Both methods throw a SerializationException– Both methods require a Stream object as a parameter
• So that the BinaryFormatter can access the correct stream
65
2006 Pearson Education, Inc. All rights reserved.
18.8 Creating a Sequential-Access File Using Object Serialization
• Serializable objects– Must include [Serializable] attribute or implement
interface ISerializable• Indicates to the CLR that objects of class can be serialized• Classes that write to or read from a stream must include this in their
declarations
– Must ensure that every instance variable of the class is also serializable
• Check class declaration to ensure that the type is serializable for variables of reference types
• All simple-type variables and strings are serializable• By default, array objects are serializable
– If the array contains references to other objects, those objects may or may not be serializable
66
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.13: RecordSerializable.cs
2 // Serializable class that represents a data record.
3 using System;
4
5 [ Serializable ]
6 public class RecordSerializable
7 {
8 private int account;
9 private string firstName;
10 private string lastName;
11 private decimal balance;
12
13 // parameterless constructor sets members to default values
14 public RecordSerializable()
15 : this( 0, "", "", 0.0M )
16 {
17 } // end constructor
18
19 // overloaded constructor sets members to parameter values
20 public RecordSerializable( int accountValue, string firstNameValue,
21 string lastNameValue, decimal balanceValue )
22 {
23 Account = accountValue;
24 FirstName = firstNameValue;
25 LastName = lastNameValue;
26 Balance = balanceValue;
27 } // end constructor
Outline
RecordSerializable.cs
(1 of 3)
Indicate to the CLR that objects of this class can be serialized
private instance values representing all the information for a record
Initializes the private instance variables’ value
67
2006 Pearson Education, Inc. All rights reserved.
28
29 // property that gets and sets Account
30 public int Account
31 {
32 get
33 {
34 return account;
35 } // end get
36 set
37 {
38 account = value;
39 } // end set
40 } // end property Account
41
42 // property that gets and sets FirstName
43 public string FirstName
44 {
45 get
46 {
47 return firstName;
48 } // end get
49 set
50 {
51 firstName = value;
52 } // end set
53 } // end property FirstName
Outline
RecordSerializable.cs
(2 of 3)
Property for private instance variable account
Property for private instance variable firstName
68
2006 Pearson Education, Inc. All rights reserved.
54
55 // property that gets and sets LastName
56 public string LastName
57 {
58 get
59 {
60 return lastName;
61 } // end get
62 set
63 {
64 lastName = value;
65 } // end set
66 } // end property LastName
67
68 // property that gets and sets Balance
69 public decimal Balance
70 {
71 get
72 {
73 return balance;
74 } // end get
75 set
76 {
77 balance = value;
78 } // end set
79 } // end property Balance
80 } // end class RecordSerializable
Outline
RecordSerializable.cs
(3 of 3)
Property for private instance variable lastName
Property for private instance variable balance
69
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 18.2
It is a logic error to open an existing file for output when the user wishes to preserve the file. The original file’s contents will be lost.
70
2006 Pearson Education, Inc. All rights reserved.
1 // Fig 18.14: CreateFileForm.cs
2 // Creating a sequential-access file using serialization.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6 using System.Runtime.Serialization.Formatters.Binary;
7 using System.Runtime.Serialization;
8 using BankLibrary;
9
10 public partial class CreateFileForm : BankUIForm
11 {
12 // object for serializing Records in binary format
13 private BinaryFormatter formatter = new BinaryFormatter();
14 private FileStream output; // stream for writing to a file
15
16 // parameterless constructor
17 public CreateFileForm()
18 {
19 InitializeComponent();
20 } // end constructor
21
22 // handler for saveButton_Click
23 private void saveButton_Click( object sender, EventArgs e )
24 {
25 // create dialog box enabling user to save file
26 SaveFileDialog fileChooser = new SaveFileDialog();
27 DialogResult result = fileChooser.ShowDialog();
28 string fileName; // name of file to save data
29
30 fileChooser.CheckFileExists = false; // allow user to create file
Outline
CreateFileForm.cs
(1 of 8)
Using specialize namespaces for serialization
Create a BinaryFormatter object for writing serialized object
Create a FileStream object for connecting to a file
Prompt user for location to save file
71
2006 Pearson Education, Inc. All rights reserved.
31
32 // exit event handler if user clicked "Cancel"
33 if ( result == DialogResult.Cancel )
34 return;
35
36 fileName = fileChooser.FileName; // get specified file name
37
38 // show error if user specified invalid file
39 if ( fileName == "" || fileName == null )
40 MessageBox.Show( "Invalid File Name", "Error",
41 MessageBoxButtons.OK, MessageBoxIcon.Error );
42 else
43 {
44 // save file via FileStream if user specified valid file
45 try
46 {
47 // open file with write access
48 output = new FileStream( fileName,
49 FileMode.OpenOrCreate, FileAccess.Write );
50
51 // disable Save button and enable Enter button
52 saveButton.Enabled = false;
53 enterButton.Enabled = true;
54 } // end try
Outline
CreateFileForm.cs
(2 of 8)
Open the file if the file exists or create the file if it does not exist
Indicates that the program can perform only write operations with this object
Notify user of any problems with the appropriate message
Determine if user pressed “Cancel”
72
2006 Pearson Education, Inc. All rights reserved.
55 // handle exception if there is a problem opening the file
56 catch ( IOException )
57 {
58 // notify user if file does not exist
59 MessageBox.Show( "Error opening file", "Error",
60 MessageBoxButtons.OK, MessageBoxIcon.Error );
61 } // end catch
62 } // end else
63 } // end method saveButton_Click
64
65 // handler for enterButton Click
66 private void enterButton_Click( object sender, EventArgs e )
67 {
68 // store TextBox values string array
69 string[] values = GetTextBoxValues();
70
71 // Record containing TextBox values to serialize
72 RecordSerializable record = new RecordSerializable();
73
74 // determine whether TextBox account field is empty
75 if ( values[ ( int ) TextBoxIndices.ACCOUNT ] != "" )
76 {
77 // store TextBox values in Record and serialize Record
78 try
79 {
80 // get account number value from TextBox
81 int accountNumber = Int32.Parse(
82 values[ ( int ) TextBoxIndices.ACCOUNT ] );
Outline
CreateFileForm.cs
(3 of 8)
73
2006 Pearson Education, Inc. All rights reserved.
83
84 // determine whether accountNumber is valid
85 if ( accountNumber > 0 )
86 {
87 // store TextBox fields in Record
88 record.Account = accountNumber;
89 record.FirstName = values[ ( int ) TextBoxIndices.FIRST ];
90 record.LastName = values[ ( int ) TextBoxIndices.LAST ];
91 record.Balance = Decimal.Parse( values[
92 ( int ) TextBoxIndices.BALANCE ] );
93
94 // write Record to FileStream ( serialize object )
95 formatter.Serialize( output, record );
96 } // end if
97 else
98 {
99 // notify user if invalid account number
100 MessageBox.Show( "Invalid Account Number", "Error",
101 MessageBoxButtons.OK, MessageBoxIcon.Error );
102 } // end else
103 } // end try
104 // notify user if error occurs in serialization
105 catch ( SerializationException )
106 {
107 MessageBox.Show( "Error Writing to File", "Error",
108 MessageBoxButtons.OK, MessageBoxIcon.Error );
109 } // end catch
Outline
CreateFileForm.cs
(4 of 8)
Write the RecordSerializable object to the output file
Catch SerializationException if an exception is thrown during
serialization
74
2006 Pearson Education, Inc. All rights reserved.
110 // notify user if error occurs regarding parameter format
111 catch ( FormatException )
112 {
113 MessageBox.Show( "Invalid Format", "Error",
114 MessageBoxButtons.OK, MessageBoxIcon.Error );
115 } // end catch
116 } // end if
117
118 ClearTextBoxes(); // clear TextBox values
119 } // end method enterButton_Click
120
121 // handler for exitButton Click
122 private void exitButton_Click( object sender, EventArgs e )
123 {
124 // determine whether file exists
125 if ( output != null )
126 {
127 // close file
128 try
129 {
130 output.Close();
131 } // end try
132 // notify user of error closing file
133 catch ( IOException )
134 {
135 MessageBox.Show( "Cannot close file", "Error",
136 MessageBoxButtons.OK, MessageBoxIcon.Error );
137 } // end catch
138 } // end if
Outline
CreateFileForm.cs
(5 of 8)
75
2006 Pearson Education, Inc. All rights reserved.
139
140 Application.Exit();
141 } // end method exitButton_Click
142 } // end class CreateFileForm
Outline
CreateFileForm.cs
(6 of 8)
(a)
BankUI graphical user interface
76
2006 Pearson Education, Inc. All rights reserved.
Outline
CreateFileForm.cs
(7 of 8)
(b)
SaveFileDialog
Files and directories
(c) (d)
77
2006 Pearson Education, Inc. All rights reserved.
Outline
CreateFileForm.cs
(8 of 8)
(d)(g)
(e) (f)
78
2006 Pearson Education, Inc. All rights reserved.
18.9 Reading and Deserializing Data from a Sequential-Access Text File
•BinaryFormatter’s Method Deserialize – Reads a serialized object from a stream and reforms the
object in memory– Returns a reference of type object
• Must be cast to the appropriate type to manipulate the object
79
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 18.15: ReadSequentialAccessFileForm.cs
2 // Reading a sequential-access file using deserialization.
3 using System;
4 using System.Windows.Forms;
5 using System.IO;
6 using System.Runtime.Serialization.Formatters.Binary;
7 using System.Runtime.Serialization;
8 using BankLibrary;
9
10 public partial class ReadSequentialAccessFileForm : BankUIForm
11 {
12 // object for deserializing Record in binary format
13 private BinaryFormatter reader = new BinaryFormatter();
14 private FileStream input; // stream for reading from a file
15
16 // parameterless constructor
17 public ReadSequentialAccessFileForm()
18 {
19 InitializeComponent();
20 } // end constructor
21
22 // invoked when user clicks Open button
23 private void openButton_Click( object sender, EventArgs e )
24 {
25 // create dialog box enabling user to open file
26 OpenFileDialog fileChooser = new OpenFileDialog();
27 DialogResult result = fileChooser.ShowDialog();
28 string fileName; // name of file containing data
Outline
ReadSequential AccessFileForm.cs
(1 of 6)Used to read serialized objects
80
2006 Pearson Education, Inc. All rights reserved.
29
30 // exit event handler if user clicked Cancel
31 if ( result == DialogResult.Cancel )
32 return;
33
34 fileName = fileChooser.FileName; // get specified file name
35 ClearTextBoxes();
36
37 // show error if user specified invalid file
38 if ( fileName == "" || fileName == null )
39 MessageBox.Show( "Invalid File Name", "Error",
40 MessageBoxButtons.OK, MessageBoxIcon.Error );
41 else
42 {
43 // create FileStream to obtain read access to file
44 input = new FileStream(
45 fileName, FileMode.Open, FileAccess.Read );
46
47 openButton.Enabled = false; // disable Open File button
48 nextButton.Enabled = true; // enable Next Record button
49 } // end else
50 } // end method openButton_Click
Outline
ReadSequential AccessFileForm.cs
(2 of 6)
81
2006 Pearson Education, Inc. All rights reserved.
51
52 // invoked when user clicks Next button
53 private void nextButton_Click( object sender, EventArgs e )
54 {
55 // deserialize Record and store data in TextBoxes
56 try
57 {
58 // get next RecordSerializable available in file
59 RecordSerializable record =
60 ( RecordSerializable ) reader.Deserialize( input );
61
62 // store Record values in temporary string array
63 string[] values = new string[] {
64 record.Account.ToString(),
65 record.FirstName.ToString(),
66 record.LastName.ToString(),
67 record.Balance.ToString()
68 };
69 // copy string array values to TextBox values
70 SetTextBoxValues( values );
71 } // end try
72 // handle exception when there are no Records in file
73 catch( SerializationException )
74 {
75 input.Close(); // close FileStream if no Records in file
76 openButton.Enabled = true; // enable Open File button
77 nextButton.Enabled = false; // disable Next Record button
78
79 ClearTextBoxes();
Outline
ReadSequential AccessFileForm.cs
(3 of 6)
Use method Deserialize to read serialized data
Catch SerializationException if an exception is thrown during
serialization
82
2006 Pearson Education, Inc. All rights reserved.
80
81 // notify user if no Records in file
82 MessageBox.Show( "No more records in file", "",
83 MessageBoxButtons.OK, MessageBoxIcon.Information );
84 } // end catch
85 } // end method nextButton_Click
86 } // end class readSequentialAccessFileForm
Outline
ReadSequential AccessFileForm.cs
(4 of 6)
83
2006 Pearson Education, Inc. All rights reserved.
Outline
ReadSequential AccessFileForm.cs
(5 of 6)
84
2006 Pearson Education, Inc. All rights reserved.
Outline
ReadSequential AccessFileForm.cs
(6 of 6)