2009 pearson education, inc. all rights reserved. 1 ch.19 files and streams many slides modified by...

108
2009 Pearson Education, Inc. All rights rese 1 Ch.1 9 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message). Slides added by L.Lilien are © 2006-2010 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

Upload: todd-horatio-hicks

Post on 30-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

1

Ch.19Ch.19

Files and Streams

Many slides modified by Prof. L. Lilien (even many without explicit message).

Slides added by L.Lilien are © 2006-2010 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

Page 2: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

2

19.1   Introduction

19.2   Data Hierarchy

19.3   Files and Streams

19.4   ** SKIP ** Classes File and Directory

19.5   Creating a Sequential-Access Text File

19.6   Reading Data from a Sequential-Access Text File

19.7   ** SKIP** Case Study: Credit Inquiry Program Using LINQ

19.8   Serialization

19.9   Creating a Sequential-Access File Using Object Serialization

19.10 Reading and Deserializing Data from a Binary File

Page 3: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

3

19.1 Introduction• Variables and arrays are only temporary

– Lost during garbage collection or when a program terminates

• Files used for long term storage– Called persistent data– Stored on secondary storage devices

- Can store large amounts of dataMuch more than in variables or arrays in program memory

- Can “carry” data between program executions

• This chapter deals with:– Sequential-access files

Ed. 1 only: Random-access files (not covered in CS 1120)– File processing features– Stream-input and stream-output features

Slide modified by L. Lilien

Page 4: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

419.2 Data Hierarchy (see Fig – next page)

– Bit (binary digit) : either ‘1’ or ‘0’ - All data represented as combination of bits- Easy for electronic devices to understand

– Byte: eight bits– Character: two bytes in C# (bec. C# uses Unicode )

- Character set: set of all characters used to program and represent data on a particular computer

– Field: composition of characters that conveys a meaning– Record: composition of several, related fields

- Record key: identifies record (ties it to a given entity)

– File: group of related records- Sequential file: typically, records stored in order of record keys (cf.

slides 25-27)

– Database: a collection of related files (managed by DBMS)- Database management system (DBMS) - collection of programs

designed to create and manage databases

CO

MP

LE

XIT

Y

Slide modified by L. Lilien

Page 5: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

519.2 Data Hierarchy

Fig. 19.1 Data hierarchy.

Randy Red

Iris Orange

Judy Green

Tom Blue

Sally Black

file

Judy Green record

Judy field

01001010 (ASCII for J) byte

1 bit

a collection of related files database

Slide modified by L. Lilien

Page 6: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

6

19.3 Files and Streams

• File – a sequential stream of bytes

– File end determined by:- an end-of-file marker - file length - number of bytes n in the file

Recorded in system data structure

• When file opened in C#:– Creates an object– Associates a stream with that object

Slide modified by L. Lilien

Fig. 19.2 C#’s view of an n-byte file.

0 1 2 3 4 5 6 7 8 n - 1……

end-of -file marker (a.k.a. a sentinel value)

Page 7: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

719.3 Files and Streams

• When a console application starts, 3 object of class Stream (see next slide) are created

– They facilitate communication:the program <----> a particular file or device

– These 3 stream objects are accessed via Console properties:- Property Console.In: returns standard input stream object

Enables a program to input from the keyboard

- Property Console.Out: returns standard output stream objectEnables a program to output to the screen

- Property Console.Error: returns standard error stream objectEnables a program to output error messages to the

screen

• We have already used Console.In and Console.Out– Console.Read and Console.ReadLine use Console.In implicitly– Console.Write and Console.WriteLine use Console.Out implicitly

Slide modified by L. Lilien

Page 8: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

++OPTIONAL++ 19.3 Files and Streams

• Console Class [http://msdn.microsoft.com/en-us/library/system.console.aspx]

- public static class Console

• Console I/O Streams [http://msdn.microsoft.com/en-us/library/system.console.aspx]

– When a console application starts, the operating system automatically associates three I/O streams with the console :

- the standard input stream — application can read user input from it

- the standard output stream — application can write normal data to it

- the standard error output stream — application can write error data to it

– These streams are presented to your application as the values of the In, Out, and Error properties [of the Console class]

8

Page 9: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

++OPTIONAL++

• Console.In property http://msdn.microsoft.com/en-us/library/system.console.in.aspx

– Gets the standard input stream.

– public static TextReader In { get; } // In is of type TextReader

– set to the standard input stream by default

• Console.Out property http://msdn.microsoft.com/en-us/library/system.console.out.aspx

– public static TextWriter Out { get; } // Out is of type TextWriter

– set to the standard output stream by default

• Console.Error Property http://msdn.microsoft.com/en-us/library/system.console.error.aspx

– public static TextWriter Error { get; } // Error is of type TextWriter

– set to the standard error stream by default

9

Page 10: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

1019.3 Files and Streams

• Namespace System.IO namespace is needed for file processing– Includes definitions for stream classes such as:

- Class StreamReader - for text input from a fileInherits from abstract class TextReader

Console.In is a Console property of type TextReader

- Class StreamWriter - for text output to a fileInherits from abstract class TextWriter

Console.Out and Console.Error are Console properties of type of TextWriter

- Class FileStream - for text input/output from/to a fileInherits from abstract class Stream (discussed next)

Example:

private FileStream output;

output = new FileStream( fileName,

FileMode.OpenOrCreate, FileAccess.Write );

– Files are opened by creating objects of these stream classesSlide modified by L. Lilien

Page 11: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

1119.3 Files and Streams

• Abstract class Stream (System.IO.Stream) - allows for representation of streams as bytes

– Bytes (representing streams) are stored in files/memory/buffer

or– Bytes (representing streams) are retrieved from files/memory/buffer

• Concrete classes derived from Stream:

1) Class FileStream: read/write to/from sequential-access and random-access files

- inherits from abstract class Stream

2) Class MemoryStream – transfers data directly to/from memory

- Inherits from abstract class Stream - Much faster than data transfer, e.g., to/from disk

[cont.] Slide modified by L. Lilien

Page 12: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

12

3) Class BufferedStream - uses buffering to transfer data to/from a stream- Inherits from abstract class Stream

- Buffering is a technique enhancing performance of I/O operations I/O = input/output (from/to an output device holding a file)

Each output operation is directed to a buffer Buffer is a region in memory - So transfer (being a memory transfer) is fast! So we (temporarily) write only into memory instead of writing

to (a file on) an output device

- (Fast) output to the buffer (in memory) is called logical output- (Slower) output from a buffer to an output device is called physical

output Performed when buffer full (or when program

terminates)

- Q: Why buffering improves performance?- A: Bec. there are many more (fast) logical outputs than (slower) physical

outputs

**SKIP** 19.3 Files and Streams

Slide modified by L. Lilien

Page 13: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

13

*** SKIP *** 19.4 Classes File and Directory

Slide modified by L. Lilien

Page 14: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

14

19.5 Creating a Sequential-Access File

• In C#, files have no structure

– Just a sequence of bytes

- No record structure

• Programmers have to structure files to meet the requirements of applications

– Define/create your own record structure within a file- Using text and special characters to “organize” records within files

Slide modified by L. Lilien

Page 15: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

15

DIGRESSION: Enumeration• Enumeration declaration:         

          <modifier> enum <enum_name> : <underlying_type>// modifier: private, public, protected or internal

           {                        <Enumeration list>            {

• Example 1          enum Months // default underlying type is int

             {                        JAN, FEB, MAR, APR            }

• By default the first enumerator represented by the value of 0 and the value of each successive enumerator is increased by 1.

– In Example 1, the value of JAN is 0, of FEB is 1, …, of APR is 3• Can override default values representing enumerators

– Example 2            enum Months             {                         JAN = 10, FEB = 20, MAR = 30, APR = 40              }  

• In Example 2 (in contrast to Example 1), the value of JAN is 10, of FEB is 20, …

[cf. Rajesh V. S. - see http://www.c-sharpcorner.com/Language/EnumeratorsInCsharpRVS.asp]Slide added by L. Lilien

Page 16: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

16

DIGRESSION: Enumeration – cont.

• An explicit cast is needed to convert from underlying enum type to another type, e.g., integer type. (This is why the enum types are type-safe in C#.)

– Small example            int x = Months.JAN; is not a valid C# statement          int x = ( int ) Months.JAN ; is a valid C# statement 

• Larger example (incl. converting and printing enum values)

using System;enum Months : long // non-default underlying type – 64-bit size

{ JAN = 10, FEB = 20} class MyClient{      public static void Main()      {            long x = ( long ) Months.JAN;            long y = ( long ) Months.FEB;            Console.WriteLine(“JAN value = {0}, FEB value = {1}", x, y);      }} 

Output: JAN value = 10, FEB value = 20

[cf. Rajesh V. S. - see http://www.c-sharpcorner.com/Language/EnumeratorsInCsharpRVS.asp]

Slide added by L. Lilien

Page 17: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

1719.5 Creating a Sequential-Access Text File

• Examples: File processing in a bank-account maintenance application

– Class BankUIForm - a reusable

windows form for examples

(p. 925, ed.3)

– Class Record – used for writing/reading records to/from a sequential file (cf. the slides below)

– Both classes compiled into a DLL library (“namespace”) named BankLibrary

Slide added by L. Lilien

Page 18: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

1819.5 Creating a Sequential-Access Text File

• Other classes in examples in this and next Sections

– Derived from BankUIForm:

- public class CreateFileForm : BankUIForm (p.929, ed.3)

- public class ReadSequentialAccessFileForm : BankUIForm (p.935, ed.3)

Slide added by L. Lilien

Figure: GUIs for

CreateFileForm and ReadSequentialAccessFileForm

add 3 buttons to BankUIForm’s GUI

(compare this figure with the figure on the preceding slide)

Page 19: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

19** SKIP ** 19.5 Creating a Sequential-Access Text File

• ** SKIP ** Other classes in examples in this and next Sections– Not derived from BankUIForm: (Sec. 19.7, p. 941, ed.3)

- public class CreditInquiryForm : Form- Or:- public class CreditInquiryForm : Systems.Windows.Forms.Form

Slide added by L. Lilien

Page 20: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

20

1 // Fig. 19.7: BankUIForm.cs

2 // A reusable Windows Form for the examples in this chapter.

3 using System;

4 using System.Windows.Forms;

5

6 namespace BankLibrary

7 {

8 public partial class BankUIForm : Form // Form = System.Windows.Forms.Form

9 {

10 protected int TextBoxCount = 4; // number of TextBoxes on Form (see Fig.)

11 // RECALL: ‘protected’ allows access by derived classes

12 // enumeration constants specify TextBox indices

13 public enum TextBoxIndices

14 {

15 ACCOUNT, // value: 0

16 FIRST, // value: 1

17 LAST, // value: 2

18 BALANCE // value: 3

19 } // end enum

Outline

BankUIForm.cs

(1 of 5 )

19.5.A Class BankUIForm• Reusable class BankUIForm inherits from a base-class GUI named Form

• A partial class (line 8 below) (cf. p. 628-ed.3; also p. 733-ed.3 – more details than covered here)

- Means that the class is split among files – not contained in a single file- Reason for splitting:

- Part of class created by using Visual Studio’s Toolbox and Properties windows (not by “hand-writing” code)

- Part of class manually coded (“hand-written”)- These parts placed in separate files

Above‘partial class’ text added by L. Lilien

Slide moified by L. Lilien

Page 21: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

21

20

21 // parameterless constructor

22 public BankUIForm()

23 {

24 InitializeComponent(); // initializes form

25 } // end constructor

26

27 // clear all TextBoxes

28 public void ClearTextBoxes()

29 {

30 // iterate through every Control on form

31 foreach ( Control guiControl in Controls )

32 {

33 // determine whether Control is TextBox (not a Label)

34 if ( guiControl is TextBox )

35 {

36 // clear TextBox – notice use of cast

37 ( ( TextBox ) guiControl ).Clear();

38 } // end if

39 } // end for

40 } // end method ClearTextBoxes

Outline

BankUIForm.cs

(2 of 5 )

Slide modified by L. Lilien

Page 22: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

2241

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 // why ‘+1’ above?? Seems to be an error.

52 // set array values if array has correct length

53 else

54 {

55 // set array values to textbox values

56 accountTextBox.Text = values[ ( int ) TextBoxIndices.ACCOUNT ];

57 // cast used; TextBoxIndices.ACCOUNT is 0 (see slide ‘-2’, l.15)

Outline

BankUIForm.cs

(3 of 5 )

Slide modified by L. Lilien

58 firstNameTextBox.Text = values[ ( int )

59 TextBoxIndices.FIRST ];

60 lastNameTextBox.Text = values[ ( int ) TextBoxIndices.LAST ];

61 balanceTextBox.Text = values[ ( int )

62 TextBoxIndices.BALANCE ];

63 } // end else

64 } // end method SetTextBoxValues

65

Page 23: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

23

65

66 // return textbox values as string array

67 public string[] GetTextBoxValues()

68 {

69 string[] values = new string[ TextBoxCount ];

70 // TextBoxCount above gives string array size

71 // copy textbox fields to string array – notice casts

72 values[ ( int ) TextBoxIndices.ACCOUNT ] = accountTextBox.Text;

73 values[ ( int ) TextBoxIndices.FIRST ] = firstNameTextBox.Text;

74 values[ ( int ) TextBoxIndices.LAST ] = lastNameTextBox.Text;

75 values[ ( int ) TextBoxIndices.BALANCE ] = balanceTextBox.Text;

76

77 return values;

78 } // end method GetTextBoxValues

79 } // end class BankUIForm

80 } // end namespace BankLibrary

Outline

BankUIForm.cs

(4 of 5 )

Slide modified by L. Lilien

Page 24: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

24Outline

BankUIForm.cs

(5 of 5 )

The form generated by BankUIForm.cs

Slide modified by L. Lilien

• To enable reusing BankUIForm: (p. 927, ed.3)

- Compile the GUI into BankLibrary DLL (see namespace BankLibrary on prev. slides)

- Create the project ‘BankLibrary’ of type Windows Control Library- Later, in any other project using it, add a reference to the project

‘BankLibrary’ - (see ‘using BankLibrary’ in slides below)

Page 25: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

25

19.5.B Class Record

• Class Record- Used in the next few examples

- For maintaining the information in each record that is written to or read from a file

• Also belongs to the BankLibrary DLL- Compile the GUI into ‘BankLibrary’ DLL as before (prev.

slide)- So it is located in the same project as BankUIForm

Slide modified by L. Lilien

Page 26: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

26

• RECALL: Auto-implemented property (lines 8-18, next slide)

- For example:

// An auto-implemented Account property public int Account { get; set; }

- It is equivalent to this “manually-implemented” property: // “manually-implemented” Account property public int Account { get { return account; } set { account = value; }

}

Slide modified by L. Lilien

Page 27: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

27

1 // Fig. 19.8: Record.cs

2 // Class that represents a data record.

3

4 namespace BankLibrary

5 {

6 public class Record

7 {

8 // auto-implemented Account property

9 public int Account { get; set; }

10

11 // auto-implemented FirstName property

12 public string FirstName { get; set; }

13

14 // auto-implemented LastName property

15 public string LastName { get; set; }

16

17 // auto-implemented Balance property

18 public decimal Balance { get; set; }

Outline

Record.cs

(1 of 2 )

Slide modified by L. Lilien

Page 28: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

28

19

20 // overloaded parameterless constructor sets members to default values

21 public Record()

22 : this( 0, string.Empty, string.Empty, 0M ) // RECALL: OM = decimal 0.0

23 { // RECALL: ‘this’ means using another constructor (from lines 27-34)

24 } // end constructor

25

26 // overloaded 4-parameter constructor sets members to parameter values

27 public Record( int accountValue, string firstNameValue,

28 string lastNameValue, decimal balanceValue )

29 { // incorrect name ‘RecordSerializable’ (textbook p.928-ed.3) corrected

30 Account = accountValue;

31 FirstName = firstNameValue;

32 LastName = lastNameValue;

33 Balance = balanceValue;

34 } // end constructor

35 } // end class Record

36 } // end namespace BankLibrary

Outline

Record.cs

(2 of 2 )

Slide modified by L. Lilien

Page 29: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

2919.5.C Using a Character Stream to Create an Output File

• Class CreateFileForm (Fig. 19.9 - below)

- Uses instances of class Record

- Uses Record for creating a sequential-access file

- Class CreateFileForm might be used for accounts-receivable system- Organizes into records data regarding money owed by company’s credit

clients

- For each client we have:

1) account number,

2) first name,

3) last names, and

4) balance (owed to company)

Slide modified by L. Lilien

Page 30: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

30

Slide modified by L. Lilien

Page 31: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

31DIGRESSION: The using statement (p. 610-ed.3)

Slide added by L. Lilien

• The using statement simplifies releasing resources after their use• Do not confuse the using statement with the using directive

• The general form of a using statement is:

using ( ExampleObject exo = new ExampleObject() ){ exo.SomeMethod();

}

• The above using statement code is equivalent to

{ ExampleObject exo = new ExampleObject();

try { exo.SomeMethod(); } finally { if ( exo != null ) ( ( IDisposable ) exo ).Dispose(); } // above line releases resource}

Page 32: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

32

GUI of CreateFileForm enhanced with buttons Save As, Enter and Exit

Slide modified by L. Lilien

GUI of BankUIForm

• Class CreateFileForm enhances GUI of class BankUIForm with buttons Save As, Enter and Exit

Page 33: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

33

CreateSequentialAccessFile.cs

Program Output

Slide modified by L. Lilien

GUI for the Next Program (Fig. 17.9 [ed.1] - CreateSequentialAccessFile.cs):

Creating a sequential-access file = Writing data into a sequential-access file – Example

User clicks the “Save As” button in the “Creating a Sequential File” window to start file creation process.

File selection dialog window (next slide) appears.

Page 34: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

34

CreateSequentialAccessFile.cs

Program Output

Slide modified by L. Lilien

User creates a file by selecting its drive & directory (by pointing

& clicking), and by typing its filename ‘clients.txt’ (into the ‘File

name:’ text box) in the displayed file selection dialog window named “Save As”.

SaveFileDialog

By clicking on directories, select the directory.

Then, type file name – it is the created file in the selected directory

Type file name

Page 35: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

35

After the file location and name are entered, data (records) are entered as follows:

User enters data into 4 textboxes, then clicks on ‘Enter’.

(For simplicity, user enters data in the ‘Account’ number order; ‘Account’ is the record key)

Program stores data in 4 fields of Record 1 (with key: 100) in a file.

User enters data into 4 textboxes, then clicks on ‘Enter’.

Program stores data in 4 fields of Record 2 (with key: 200) in a file.

Slide added by L. Lilien

Page 36: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

36

User enters data into 4 textboxes, then clicks on ‘Enter’.

Program stores data in 4 fields of Record 3 (with key: 399) in a file.

User enters data into 4 textboxes, then clicks on ‘Enter’.

Program stores data in 4 fields of Record 4 (with key: 400) in a file.

Slide added by L. Lilien

Page 37: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

37

Slide added by L. Lilien

User enters data into 4 textboxes, then clicks on ‘Enter’.

Program stores data in 4 fields of Record 5 (with key: 500) in a file.

User clicks on ‘Exit’ to terminate program execution.

Program terminates, but all five records remain stored safely.

Page 38: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

38

1 // Fig. 19.9: CreateFileForm.cs

2 // Creating a sequential-access file.

3 using System;

4 using System.Windows.Forms;

5 using System.IO;

6 using BankLibrary; // allows to use BankUIForm and Record

7

8 namespace CreateFile

9 {

10 public partial class CreateFileForm : BankUIForm

11 {

12 private StreamWriter fileWriter; // used below to write data to text file

13

14 // parameterless constructor

15 public CreateFileForm()

16 {

17 InitializeComponent(); // initializes form

18 } // end constructor

19

Outline

CreateFileForm.cs

(1 of 11 )

Slide modified by L. Lilien

Page 39: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

39

20 // event handler for Save Button

21 private void saveButton_Click( object sender, EventArgs e )

22 {

23 // create and show dialog box enabling user to save file

24 DialogResult result; // result of SaveFileDialog

25 string fileName; // name of file containing data

26

27 using ( SaveFileDialog fileChooser = new SaveFileDialog() )

28 {

29 fileChooser.CheckFileExists = false; // let user create (and name) file 30 result = fileChooser.ShowDialog(); // returns result showing whether // Save or Cancel clicked 31 fileName = fileChooser.FileName; // gets name of file to save data

32 } // end using

33

Outline

CreateFileForm.cs

(2 of 11 )Class SaveFileDialog is used for selecting files.

SaveFileDialog‘s method ShowDialog displays the dialog (the window shown below) and returns a DialogResult specifying which button (Save or Cancel) was clicked to close the dialog.

Slide modified by L. Lilien

SaveFileDialog

By clicking on directories, select the directory.

Then, type file name – it is the created file in the selected

directory

Type file name

Later compare lines 29-31 to lines 29-30 in Fig. 19.11 (reading existing file) .

No line corresponding to l.29 there (bec. we are not creating a file there, but use name of an existing file.)

Page 40: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

4034 // If user clicked "Save" (clicking “Save” means “OK”), then …

35 if ( result == DialogResult.OK )

36 {

37 // show error if user specified invalid file

38 if ( fileName == string.Empty )

39 MessageBox.Show( "Invalid File Name", "Error",

40 MessageBoxButtons.OK, MessageBoxIcon.Error );

41 else

42 {

43 // save file via FileStream if user specified valid file

44 try // fileName (a full path) was entered via SaveFileDialog

45 { // 2 steps to write into file:

46 // (step 1) open file with write access

47 FileStream output = new FileStream( fileName,

48 FileMode.OpenOrCreate, FileAccess.Write );

49

50 // (step 2) “connect” file to stream of data to be written

51 fileWriter = new StreamWriter( output );

52 // StreamWriter fileWriter is declared on l. 12

53 // disable Save button and enable Enter button

54 saveButton.Enabled = false;

55 enterButton.Enabled = true;

56 } // end try

Outline

CreateFileForm.cs

(3 of 11 )

The constant FileMode.OpenOrCreate indicates that the FileStream should open the file if it exists or create the file if it does not.

WARNING: FileMode.Open OrCreate will overwrite file contents if file exists.

To avoid overwriting existing file, use FileMode.Append

Slide modified by L. Lilien

Page 41: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

41

57 // handle exception if there is a problem opening the file

58 catch ( IOException )

59 {

60 // notify user if file does not exist

61 MessageBox.Show( "Error opening file", "Error",

62 MessageBoxButtons.OK, MessageBoxIcon.Error );

63 } // end catch

64 } // end else

65 } // end if

66 } // end method saveButton_Click

67

68 // handler for enterButton Click

69 private void enterButton_Click( object sender, EventArgs e )

70 {

71 // store TextBox values string array

72 string[] values = GetTextBoxValues(); // method from BankUIForm class

73

74 // Record containing TextBox values to serialize

75 Record record = new Record(); // uses class Record of Fig. 19.8

76

Outline

CreateFileForm.cs

(4 of 11 )

An IOException is thrown if there is a problem opening the file or creating the StreamWriter.

Slide modified by L. Lilien

enterButton_Click is entered after a user clicks “Enter” following writing data into text boxes on the GUI form.

Page 42: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

4277 // determine whether TextBox account field is empty

78 if ( values[ ( int ) TextBoxIndices.ACCOUNT ] != string.Empty )

79 {

80 // store TextBox values in Record and serialize Record

81 try

82 {

83 // get account-number value from TextBox

84 int accountNumber = Int32.Parse(

85 values[ ( int ) TextBoxIndices.ACCOUNT ] );

86

87 // determine whether accountNumber is valid

88 if ( accountNumber > 0 )

89 {

90 // store TextBox fields in instance of class Record (cf. Fig.19.8)

91 record.Account = accountNumber;

92 record.FirstName = values[ ( int )

93 TextBoxIndices.FIRST ];

94 record.LastName = values[ ( int )

95 TextBoxIndices.LAST ];

96 record.Balance = Decimal.Parse(

97 values[ ( int ) TextBoxIndices.BALANCE ] );

Outline

CreateFileForm.cs

(5 of 11 )

Slide modified by L. Lilien

Page 43: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

43

98

99 // write Record to file, fields separated by commas

100 fileWriter.WriteLine(

101 record.Account + "," + record.FirstName + "," +

102 record.LastName + "," + record.Balance );

103 } // end if

104 else

105 {

106 // notify user if invalid account number

107 MessageBox.Show( "Invalid Account Number", "Error",

108 MessageBoxButtons.OK, MessageBoxIcon.Error );

109 } // end else

110 } // end try

111 // notify user if error occurs in serialization

112 catch ( IOException )

113 {

114 MessageBox.Show( "Error Writing to File", "Error",

115 MessageBoxButtons.OK, MessageBoxIcon.Error );

116 } // end catch

Outline

CreateFileForm.cs

(6 of 11 )

StreamWriter method WriteLine writes a sequence of characters to a file.

Slide modified by L. Lilien

xx

Page 44: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

44

117 // notify user if error occurs regarding parameter format

118 catch ( FormatException )

119 {

120 MessageBox.Show( "Invalid Format", "Error",

121 MessageBoxButtons.OK, MessageBoxIcon.Error );

122 } // end catch

123 } // end if

124

125 ClearTextBoxes(); // clear TextBox values

126 } // end method enterButton_Click

127

128 // handler for exitButton Click

129 private void exitButton_Click( object sender, EventArgs e )

130 {

131 // determine whether file exists

132 if ( fileWriter != null )

133 {

134 try

135 {

136 // close StreamWriter and underlying file

137 fileWriter.Close();

138 } // end try

Outline

CreateFileForm.cs

(7 of 11 )

Slide modified by L. Lilien

Page 45: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

45

139 // notify user of error closing file

140 catch ( IOException )

141 {

142 MessageBox.Show( "Cannot close file", "Error",

143 MessageBoxButtons.OK, MessageBoxIcon.Error );

144 } // end catch

145 } // end if

146

147 Application.Exit();

148 } // end method exitButton_Click

149 } // end class CreateFileForm

150 } // end namespace CreateFile

Outline

CreateFileForm.cs

(8 of 11 )

a) BankUI graphical user interface with three additional controls

Slide modified by L. Lilien

AGAIN:

GUI for the Preceding Program (CreateSequentialAccessFile.cs):

Creating a sequential-access file =

= Writing data into a sequential-access file – Example

User clicks the “Save As” button in the “Creating a Sequential File” window to start file creation process.

File selection dialog window (next slide) appears.

Page 46: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

46Outline

CreateFileForm.cs

(9 of 11 )

SaveFileDialog

b) Save File dialog

Slide modified by L. Lilien

The user selects by clicking the appropriate drive, directory, and types filename (‘clients.dat’).

Then she clicks Save (or Cancel).

By clicking on directories, select the directory.

Then, type file name – it is the created file in the selected directory

Type file name

Page 47: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

47Outline

CreateFileForm.cs

(10 of 11 )

c) Account 100, "Nancy Brown", saved with a balance of -25.54

d) Account 200, "Stacey Dunn", saved with a balance of 314.33

Slide modified by L. Lilien

Page 48: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

48Outline

CreateFileForm.cs

(11 of 11 )

e) Account 399, "Doug Barker", saved with a balance of 0

f) Account 400, "Dave Smith", saved with a balance of 258.34

(g) Account 500, "Sam Stone", saved with a balance of 34.98

(h) Once all accounts are saved, the Exit button closes the application

Slide modified by L. Lilien

Page 49: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

49

19.5  Creating a Sequential-Access Text File (Cont.)

Fig. 19.10 | Sample data for the program of Fig. 19.9.

• SUMMARIZING, in the sample execution for the program in Fig. 19.9, we entered information for the five accounts shown in Fig. 19.10.

Notice that all account number values are unique! (required, since the account number field is the key)

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

399

Page 50: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

50Outline

** READ LATER **• In this application, the account number is used as the record

key—files are created and maintained in account-number order

• This program assumes that the user enters records in account-number order.

• Class CreateFileForm’s GUI enhances GUI of class BankUIForm with buttons Save As, Enter and Exit..

Page 51: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

51

19.5  Creating a Sequential-Access Text File (Cont.)

• ** READ LATER ** Things to pay attention to:

– Class SaveFileDialog is used for selecting files

– SaveFileDialog method ShowDialog displays the dialog and returns a DialogResult specifying which button was clicked to close the dialog

– A SaveFileDialog is a modal dialog —it prevents the user from interacting with any other window in the program until the user closes it.

– Method ShowDialog returns a DialogResult specifying which button (Save or Cancel) the user clicked to close the dialog.

– You can open files for text manipulation by creating objects of class FileStream

Slide modified by L. Lilien

Page 52: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

5219.5  Creating a Sequential-Access Text File (Cont.)

• ** READ LATER** Things to pay attention to:

– The constant FileMode.Open OrCreate indicates that the FileStream should open the file if it exists or create the file if it does not

- To preserve the original contents of a file, use FileMode.Append

– The constant FileAccess.Write indicates that the program can perform only write operations with the FileStream object

- There are two other FileAccess constants:FileAccess.Read for read-only accessFileAccess.ReadWrite for both read and write access

– An IOException is thrown if there is a problem opening the file or creating the StreamWriter

Page 53: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

53

19.5  Creating a Sequential-Access Text File (Cont.)

** READ LATER ** Things to pay attention to:

– StreamWriter method WriteLine writes a sequence of characters to a file

– The StreamWriter object is constructed with a FileStream argument that specifies the file to which the StreamWriter will output text

– Method Close throws an IOException if the file or stream cannot be closed properly

Page 54: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

54

** READ LATER ** 19.5  Creating a Sequential-AccessText File (Cont.)Good Programming Practice 19.1

When opening files, use the FileAccess enumerationto control user access to these files.

Good Programming Error 19.1

Failure to open a file before attempting to use it in a program is a logic error.

Page 55: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

55

** READ LATER ** 19.5  Creating a Sequential-Access Text File (Cont.)

Performance Tip 19.1

Close each file explicitly when the program no longer needs to reference it.

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.

Performance Tip 19.2

Releasing resources explicitly when they are no longer needed makes them immediately available for reuse by other programs, thus improving resource utilization.

Page 56: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

56

19.6 Reading Data from a Sequential-Access Text File

• Read data sequentially from a file

– Program starts at the beginning of a file &

reads data consecutively until the desired data is found- Sometimes necessary to do this several times during execution of a

program

– File-position pointer:- When a file (a FileStream object) is opened, its file-position pointer is set to

‘0’ (i.e., points to the first byte – the byte at offset ‘0’ – see Slide 5)

- Always points to next byte to be read from or written to fileCan be repositioned to any point only in a random access file (not

covered in CS 1120)

Page 57: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

57

19.6 Reading Data from a Sequential-Access File

• One program can create (or write) a file, and terminate

• Another program can read the file at any time – In a minute / day / week / … / year / …

– As long as the file is not deleted

• Example:

public class ReadSequentialAccessFileForm : BankUIForm

– Reads the same file that class CreateFileForm (of Fig. 19.9 [ed.3]) created (wrote)

Slide added by L. Lilien

Page 58: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

58GUI for the Next Program (ReadSequentialAccessFile.cs):

Reading from a sequential-access file - Example

When the program starts, it displays the “Reading a Sequential File” form.

User clicks the “Open File” button in the “Reading a Sequential File” window to start file opening process.

(Notice that “Next Record” is dimmed)

File selection dialog window appears (below).

Slide added by L. Lilien

User opens file by selecting its drive, directory and name - by pointing & clicking in the displayed file selection dialog window named “Open” (here, clients.txt is selected)

Page 59: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

59

After the file is opened, data (records) from the file are read as follows:

User clicks on ‘Next Record’.

Program displays Record 1, that is, 4 fields of Record 1 from the file.(As you remember, ‘Account’ is the record key and data were stored in the file in the ‘Account’ number order. Thus, the first record displayed is the one with the lowest key: 100.)

User clicks on ‘Next Record’.

Program displays Record 2 (key: 200), that is, 4 fields of Record 2 from the file.

Slide added by L. Lilien

Page 60: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

60

User clicks on ‘Next Record’.

Program displays Record 3 (key: 399) that is, 4 fields of Record 3 from the file.

User clicks on ‘Next Record’.

Program displays Record 4 (key: 400), that is, 4 fields of Record 4 from the file.

Slide added by L. Lilien

Page 61: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

61

User clicks on ‘Next Record’.

Program displays Record 5 (key: 500), that is, 4 fields of Record 5 from the file.

User clicks on ‘Next Record’.

Program shows ‘No more records in file’ since end of file has been reached.

Slide added by L. Lilien

Page 62: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

62

1 // Fig. 19.11: ReadSequentialAccessFileForm.cs

2 // Reading a sequential-access file.

3 using System;

4 using System.Windows.Forms;

5 using System.IO;

6 using BankLibrary; // allows to use classes BankUIForm and Record

7

8 namespace ReadSequentialAccessFile

9 {

10 public partial class ReadSequentialAccessFileForm : BankUIForm

11 {

12 private StreamReader fileReader; // strean for reading data from a text file

13

14 // parameterless constructor

15 public ReadSequentialAccessFileForm()

16 {

17 InitializeComponent();

18 } // end constructor

19

Outline

ReadSequentialAccessFileForm.cs

(1 of 8 )

Page 63: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

6320 // invoked when user clicks the Open button

21 private void openButton_Click( object sender, EventArgs e )

22 {

23 // create and show dialog box enabling user to open file

24 DialogResult result; // result of OpenFileDialog

25 string fileName; // name of file containing data

26

27 using ( OpenFileDialog fileChooser = new OpenFileDialog() )

28 {

29 result = fileChooser.ShowDialog();

30 fileName = fileChooser.FileName; // get specified name

31 } // end using

32

33 // check that user clicked "Open” (meaning “OK"), not “Cancel”

34 if ( result == DialogResult.OK )

35 {

36 ClearTextBoxes(); // method from BankUIForm

37

Outline

ReadSequentialAccessFileForm.cs

(2 of 8 )

Create an OpenFile Dialog, and call its ShowDialog method to display the Open dialog.

Equal to “OK” if user clicked “Open” button (not “Cancel” button) in the OpenFileDialog window

Slide modified by L. Lilien

Page 64: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

6438 // show error if user specified invalid file

39 if ( fileName == string.Empty )

40 MessageBox.Show( "Invalid File Name", "Error",

41 MessageBoxButtons.OK, MessageBoxIcon.Error );

42 else

43 {

44 try

45 {

46 // create FileStream to obtain read access to file

47 FileStream input = new FileStream(

48 fileName, FileMode.Open, FileAccess.Read );

49

50 // set file from where data is read

51 fileReader = new StreamReader( input );

52

53 openButton.Enabled = false; // disable Open File button

54 nextButton.Enabled = true; // enable Next Record button

55 } // end try

Outline

ReadSequentialAccessFileForm.cs

(3 of 8 )

Create a FileStream object, passing constant FileMode.Open as the second argument to the FileStream constructor.

Slide modified by L. Lilien

Page 65: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

6556 catch ( IOException )

57 {

58 MessageBox.Show( "Error reading from file",

59 "File Error", MessageBoxButtons.OK,

60 MessageBoxIcon.Error );

61 } // end catch

62 } // end else

63 } // end if

64 } // end method openButton_Click

65

66 // invoked when user clicks Next button

67 private void nextButton_Click( object sender, EventArgs e )

68 {

69 try

70 {

71 // get next record available in file

72 string inputRecord = fileReader.ReadLine();

73 string[] inputFields; // will store individual pieces of data

74

75 if ( inputRecord != null ) // if there is a next record

76 {

77 inputFields = inputRecord.Split( ',' ); // When file was created, we

78 // we used commas to separate fileds (cf. Fig.19.9, l.99-102)

Outline

ReadSequentialAccessFileForm.cs

(4 of 8 )

StreamReader method ReadLine reads the next line from the file.

We created record by concatenating values separated by commas.

Split separates the fields from a given record.

Now, consecutive elements of the inputFields string array store consecutive fields of a customer’s record from the file (i.e., they store: acct no, first name, last name, and balance).

Page 66: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

6679 Record record = new Record(

80 Convert.ToInt32( inputFields[ 0 ] ), inputFields[ 1 ],

81 inputFields[ 2 ], Convert.ToDecimal( 82 inputFields[ 3 ] ) ); // Field 0 (account no) requires // conversion to int, Field 3 (balance) req. conv. to string 83

84 // copy string-array values to TextBox values

85 SetTextBoxValues( inputFields ); // use method from BankUIForm

86 } // end if

87 else // inputRecord (next record) is null

88 {

89 // close StreamReader and underlying file

90 fileReader.Close();

91 openButton.Enabled = true; // enable Open File button

92 nextButton.Enabled = false; // disable Next Record button

93 ClearTextBoxes(); // method from BankUIForm

94

95 // notify user if no Records in file

96 MessageBox.Show( "No more records in file", string.Empty,

97 MessageBoxButtons.OK, MessageBoxIcon.Information );

98 } // end else

99 } // end try

Outline

ReadSequentialAccessFileForm.cs

(5 of 8 )

Construct a Record object using the data from the inputFields string array.

Display the Record values in the TextBoxes.

Page 67: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

67

100 catch ( IOException )

101 {

102 MessageBox.Show( "Error Reading from File", "Error",

103 MessageBoxButtons.OK, MessageBoxIcon.Error );

104 } // end catch

105 } // end method nextButton_Click

106 } // end class ReadSequentialAccessFileForm

107 } // end namespace ReadSequentialAccessFile

Outline

ReadSequentialAccessFileForm.cs

(6 of 8 )

AGAIN:GUI for the Preceding Program (ReadSequentialAccessFileForm.cs):

Read data from a sequential-access file – Example

a) User clicks the “Open File” button in the “Reading a Sequential File” window to start reading from a file.

File selection dialog window (next slide) appears.

Page 68: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

68Outline

ReadSequentialAccessFileForm.cs

(7 of 8 )

b) OpenFileDialog window

c) Reading account 100 d) Reading account 200

Page 69: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

69Outline

ReadSequentialAccessFileForm.cs

(8 of 8 )

g) Reading account 500

e) Reading account 399 f) Reading account 400

h) User is shown a messagebox when all records have been read

Page 70: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

70

** READ LATER ** 19.6  Reading Data from a Sequential-Access Text File (Cont.)

Things to pay attention to:

– The behavior and GUI for the Save dialog type (used for creating

file in previous section) and Open dialog type (used for reading file in this

section) are identical, except that Save is replaced by Open

– Specify read-only access to a file by passing constant FileAccess.Read as the third argument to the FileStream constructor

– StreamReader method ReadLine reads the next line from the file

Page 71: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

71

** READ LATER ** 19.6  Reading Data from a Sequential-Access Text File (Cont.)

Error-Prevention Tip 19.1

Open a file with the FileAccess.Read file-open mode if its contents should not be modified.

This prevents unintentional modification of the contents.

Page 72: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

72

** OPTIONAL ** 19.7 Case Study:Reading Data from a Sequential-Access Text File

NOTE: The slides are based on ed.1 and differ from Section 19.7 in ed.3.

To understand this OPTIONAL material, you need to read Sections 19.8 – 19.10 first (to understand Binary Formatter, serialization, & deserialization)

• RichTextBox:– Provides more functionality than TextBox– Among others, provides:

- LoadFile: method to display file contents- Find: method for searching individual strings- Can display multiple lines of text by default

TextBox by default displays one line of text only

• See input/output behavior of the program: next Slides

Page 73: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

73

CreditInquiry.cs

1 // Fig. 17.12 [ed.1]: CreditInquiry.cs2 // Read a file sequentially and display contents based on3 // account type specified by user (credit, debit or zero balances).4 5 // C# namespaces6 using System;7 using System.Drawing;8 using System.Collections;9 using System.ComponentModel;10 using System.Windows.Forms;11 using System.Data;12 using System.IO;13 using System.Runtime.Serialization.Formatters.Binary;14 using System.Runtime.Serialization;15 16 // Deitel namespaces17 using BankLibrary; // as defined for ed.1 (not ed.3)18 19 public class CreditInquiryForm : System.Windows.Forms.Form20 {21 private System.Windows.Forms.RichTextBox displayTextBox;22 23 private System.Windows.Forms.Button doneButton;24 private System.Windows.Forms.Button zeroButton;25 private System.Windows.Forms.Button debitButton;26 private System.Windows.Forms.Button creditButton;27 private System.Windows.Forms.Button openButton;28 29 private System.ComponentModel.Container components = null;30 31 // stream through which serializable data are read from file32 private FileStream input;33 34 // object for deserializing Record in binary format35 BinaryFormatter reader = new BinaryFormatter();

** OPTIONAL **

Page 74: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

74

CreditInquiry.cs

36 37 // name of file that stores credit, debit and zero balances38 private string fileName;39 40 [STAThread]41 static void Main() 42 {43 Application.Run( new CreditInquiryForm() );44 }45 46 // Visual Studio .NET generated code47 48 // invoked when user clicks Open File button49 private void openButton_Click(50 object sender, System.EventArgs e )51 {52 // create dialog box enabling user to open file53 OpenFileDialog fileChooser = new OpenFileDialog();54 DialogResult result = fileChooser.ShowDialog();55 56 // exit event handler if user clicked Cancel57 if ( result == DialogResult.Cancel )58 return;59 60 // get name from user61 fileName = fileChooser.FileName;62 63 // show error if user specified invalid file64 if ( fileName == "" || fileName == null )65 MessageBox.Show( "Invalid File Name", "Error",66 MessageBoxButtons.OK, MessageBoxIcon.Error );

User clicked open button

** OPTIONAL **

Page 75: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

7567 else68 {69 // enable all GUI buttons, except for Open file button70 openButton.Enabled = false;71 creditButton.Enabled = true;72 debitButton.Enabled = true;73 zeroButton.Enabled = true;74 }75 76 } // end method openButton_Click77 78 // invoked when user clicks credit balances,79 // debit balances or zero balances button80 private void get_Click( object sender, System.EventArgs e )81 {82 // convert sender explicitly to object of type button83 Button senderButton = ( Button )sender;84 85 // get text from clicked Button, which stores account type86 string accountType = senderButton.Text;87 88 // read and display file information89 try90 {91 // close file from previous operation92 if ( input != null )93 input.Close();94 95 // create FileStream to obtain read access to file96 input = new FileStream( fileName, FileMode.Open,97 FileAccess.Read );98 99 displayTextBox.Text = "The accounts are:\r\n";100

Reference to object that sent event

Create (open) read-only FileStream for input

** OPTIONAL **

Page 76: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

76101 // traverse file until end of file102 while ( true )103 {104 // get next Record available in file105 Record record = ( Record )reader.Deserialize( input );106 107 // store record's last field in balance108 Double balance = record.Balance;109 110 // determine whether to display balance111 if ( ShouldDisplay( balance, accountType ) )112 {113 // display record114 string output = record.Account + "\t" +115 record.FirstName + "\t" + record.LastName +116 new string( ' ', 6 ) + "\t";117 118 // display balance with correct monetary format119 output += String.Format( 120 "{0:F}", balance ) + "\r\n";121 122 // copy output to screen123 displayTextBox.Text += output; 124 }125 }126 }127 128 // handle exception when file cannot be closed129 catch( IOException )130 {131 MessageBox.Show( "Cannot Close File", "Error",132 MessageBoxButtons.OK, MessageBoxIcon.Error );133 }134

While loop to read from file

Read input from file

** OPTIONAL **

Page 77: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

77135 // handle exception when no more records136 catch( SerializationException )137 {138 // close FileStream if no Records in file139 input.Close(); 140 }141 142 } // end method get_Click143 144 // determine whether to display given record145 private bool ShouldDisplay( double balance, string accountType )146 {147 if ( balance > 0 )148 {149 // display credit balances150 if ( accountType == "Credit Balances" )151 return true;152 }153 154 else if ( balance < 0 )155 {156 // display debit balances157 if ( accountType == "Debit Balances" )158 return true;159 }160 161 else // balance == 0162 {163 // display zero balances164 if ( accountType == "Zero Balances" )165 return true;166 }167

Method to determine whether to display each record in file

No more records exception

** OPTIONAL **

Page 78: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

78168 return false;169 170 } // end method ShouldDisplay171 172 // invoked when user clicks Done button173 private void doneButton_Click(174 object sender, System.EventArgs e )175 {176 // determine whether file exists177 if ( input != null )178 {179 // close file180 try181 {182 input.Close();183 }184 185 // handle exception if FileStream does not exist186 catch( IOException )187 {188 // notify user of error closing file189 MessageBox.Show( "Cannot close file", "Error",190 MessageBoxButtons.OK, MessageBoxIcon.Error);191 }192 }193 194 Application.Exit();195 196 } // end method doneButton_Click197 198 } // end class CreditInquiryForm

Done button clicked event handler

** OPTIONAL **

Page 79: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

79Program Output ** OPTIONAL **

Page 80: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

80** OPTIONAL **

Page 81: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

81

19.8  Serialization• Sometimes it is easier to read or write entire objects than to

read and write individual fields

• C# provides a mechanism that supports reading or writing entire objects — called object serialization

• A serialized object is represented as a sequence of bytes– This sequence of bytes includes the object’s data, its type and the

types of data stored in the object

• After a serialized object has been written to a file,it can be:

– read from the file and

– deserialized back into the original object

Page 82: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

82

++READ LATER++ 19.8  Serialization (Cont.)

• Class BinaryFormatter enables entire objects to be written to or read from a stream

– Its method Serialize writes an object’s representation to a file

– Its method Deserialize reads this representation from a file and reconstructs the original object

– Both Serialize and Deserialize methods can throw a SerializationException

- If an error occurs during serialization or deserialization

Page 83: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

83

• Class BinaryFormatter : converts (serializes or deserializes) original objects from/to the corresponding Stream objects

– Method Serialize: Convert an original object into a stream object (that can later be written to a file without losing any of that object’s data)

original object --[BinaryFormatter.Serialize]--> Stream object

Note an analogy to the ‘ToString’ methods that were used to convert objects to strings. (The ‘ToString’ conversion was not for files – for converting in-memory objects to strings only!).

– Method Deserialize: Convert a stream object (read earlier from a file) into the original object

Stream object --[BinaryFormatter.Deserialize ]--> original object

Slide modified by L. Lilien

19.8  Serialization (Cont.)

Page 84: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

84

• Serialize/Deserialize methods are used when writing-to/reading-from a binary file

• The sequence of actions when writing an object to a binary file

Step 1: original --[binaryFormatter .Serialize]--> Stream object object

Step 2: Stream --[FileStream]--> binary file object

• The sequence of actions when reading an object from a binary file (reverse of above actions for writing an object to a file)

Step 1: binary file --[FileStream]--> Stream object

Step 2: Stream --[binaryFormatter .Deserialize]--> original object object

Slide added by L. Lilien

19.8  Serialization (Cont.)

Page 85: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

85

1 // Fig. 19.13: RecordSerializable.cs – very similar to Fig.19.8

2 // Serializable class that represents a data record.

3 using System; // 1st of 2 lines not in Record class of Fig. 19.8

4

5 namespace BankLibrary // To be included in this library

6 {

7 [Serializable] // 2nd of 2 lines not in Record class of Fig. 19.8

8 public class RecordSerializable // serializable version of Reccord of Fig.19.8

9 {

10 // automatic Account property

11 public int Account { get; set; }

12

A) Defining the RecordSerializable Class

• Class RecordSerializable is marked with the [Serializable] attribute

- It indicates that class objects can be serialized

Outline

RecordSerializable.cs

(1 of 2 )

19.9 Creating a Sequential-Access File Using

Object Serialization

Page 86: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

8613 // automatic FirstName property

14 public string FirstName { get; set; } 15 16 // automatic LastName property

17 public string LastName { get; set; }

18

19 // automatic Balance property

20 public decimal Balance { get; set; } 21 22 // default constructor sets members to default values

23 public RecordSerializable()

24 : this( 0, string.Empty, string.Empty, 0M )

25 {

26 } // end constructor

27

28 // 4-parameter constructor sets members to parameter values

29 public RecordSerializable( int accountValue, string firstNameValue,

30 string lastNameValue, decimal balanceValue )

31 {

32 Account = accountValue;

33 FirstName = firstNameValue;

34 LastName = lastNameValue;

35 Balance = balanceValue;

36 } // end constructor

37 } // end class RecordSerializable

38 } // end namespace BankLibrary

Outline

RecordSerializable.cs

(2 of 2 )

• NOTE: The only difference between class Record (Fig.19.8) and class

RecordSerializable (above) are two lines (Lines 3 and 7) added to the latter.

Page 87: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

87

19.9  Creating a Sequential-Access File Using Object Serialization (Cont.)

• Class for objects that we wish to serialize must either:– Include the [Serializable] attribute in its declarations

or

– Implement interface Iserializable

• ++READ LATER++ In a serializable class, you must ensure that every instance variable of the class is also serializable

– All simple-type variables and strings are serializable

– For variables of reference types, you must check their class declaration (and possbly its base class) to ensure that the type is serializable

– By default, array objects are serializable

- However, if the array contains references to other objects, you must check that those objects are serializable

Page 88: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

88

1 // Fig 19.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; // to enable using RecordSerializable and BankUIForm

9

10 namespace CreateFile

11 {

12 public partial class CreateFileForm : BankUIForm

13 {

14 // object for serializing Records in binary format

15 private BinaryFormatter formatter = new BinaryFormatter();

16 private FileStream output; // stream for writing to a file

17

B) Using a Serialization Stream to Create an Output File

• A sequential-access file with serialization (Fig. 19.14).

Outline

CreateFileForm.cs

(1 of 11 )

Create a BinaryFormatter for writing serialized objects.

RECALL: The sequence of actions when writing an object to a binary fileStep 1: original --[binaryFormatter .Serialize]--> Stream

object object

Step 2: Stream --[FileStream]--> binary object file

Page 89: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

89

18 // parameterless constructor

19 public CreateFileForm()

20 {

21 InitializeComponent();

22 } // end constructor

23

24 // handler for saveButton_Click

25 private void saveButton_Click( object sender, EventArgs e )

26 {

27 // create and show dialog box enabling user to save file

28 DialogResult result;

29 string fileName; // name of file to save data

30

31 using ( SaveFileDialog fileChooser = new SaveFileDialog() )

32 {

33 fileChooser.CheckFileExists = false; // let user create file

34

35 // retrieve the result of the dialog box

36 result = fileChooser.ShowDialog();

37 fileName = fileChooser.FileName; // get specified file name

38 } // end using

Outline

CreateFileForm.cs

(2 of 11 )

As before for text files, a user starts by clicking on “Save As” above.

Window shown below appears then, so the user can select directory and type in file name.

Page 90: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

9039

40 // ensure that user clicked "OK" (that is “Save” – not “Cancel”)

41 if ( result == DialogResult.OK )

42 {

43

44 // show error if user specified invalid file

45 if ( fileName == string.Empty )

46 MessageBox.Show( "Invalid File Name", "Error",

47 MessageBoxButtons.OK, MessageBoxIcon.Error );

48 else

49 {

50 // save file via FileStream if user specified valid file

51 try

52 {

53 // open file with write access

54 output = new FileStream( fileName,

55 FileMode.OpenOrCreate, FileAccess.Write );

56

57 // disable Save button and enable Enter button

58 saveButton.Enabled = false;

59 enterButton.Enabled = true;

60 } // end try

Outline

CreateFileForm.cs

(3 of 11 )

Page 91: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

9161 // handle exception if there is a problem opening the file

62 catch ( IOException )

63 {

64 // notify user if file could not be opened

65 MessageBox.Show( "Error opening file", "Error",

66 MessageBoxButtons.OK, MessageBoxIcon.Error );

67 } // end catch

68 } // end else

69 } // end if

70 } // end method saveButton_Click

71

72 // handler for enterButton Click

73 private void enterButton_Click( object sender, EventArgs e )

74 {

75 // store TextBox values string array

76 string[] values = GetTextBoxValues(); // method from BankUIForm

77

78 // Record containing TextBox values to serialize

79 RecordSerializable record = new RecordSerializable();

80

Outline

CreateFileForm.cs

(4 of 11 )

Page 92: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

92

81 // determine whether TextBox account field is empty

82 if ( values[ ( int ) TextBoxIndices.ACCOUNT ] != string.Empty )

83 {

84 // store TextBox values in Record and serialize Record

85 try

86 {

87 // get account-number value from TextBox

88 int accountNumber = Int32.Parse(

89 values[ ( int ) TextBoxIndices.ACCOUNT ] );

90

91 // determine whether accountNumber is valid

92 if ( accountNumber > 0 )

93 {

94 // store TextBox fields in Record

95 record.Account = accountNumber;

96 record.FirstName = values[ ( int )

97 TextBoxIndices.FIRST ];

98 record.LastName = values[ ( int )

99 TextBoxIndices.LAST ];

100 record.Balance = Decimal.Parse( values[

101 ( int ) TextBoxIndices.BALANCE ] );

102

Outline

CreateFileForm.cs

(5 of 11 )

Page 93: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

93

103 // write Record to FileStream ( serialize object )

104 formatter.Serialize( output, record );

105 } // end if

106 else

107 {

108 // notify user if invalid account number

109 MessageBox.Show( "Invalid Account Number", "Error",

110 MessageBoxButtons.OK, MessageBoxIcon.Error );

111 } // end else

112 } // end try

113 // notify user if error occurs in serialization

114 catch ( SerializationException )

115 {

116 MessageBox.Show( "Error Writing to File", "Error",

117 MessageBoxButtons.OK, MessageBoxIcon.Error );

118 } // end catch

119 // notify user if error occurs regarding parameter format

120 catch ( FormatException )

121 {

122 MessageBox.Show( "Invalid Format", "Error",

123 MessageBoxButtons.OK, MessageBoxIcon.Error );

124 } // end catch

125 } // end if

Outline

CreateFileForm.cs

(6 of 11 )

Call method Serialize to write the RecordSerializable object (record) to the output file.

RECALL: The sequence of actions when writing an object to a binary fileStep 1: original --[binaryFormatter .Serialize]--> Stream

object object

Step 2: Stream --[FileStream]--> binary object file

Page 94: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

94126

127 ClearTextBoxes(); // clear TextBox values

128 } // end method enterButton_Click

129

130 // handler for exitButton Click

131 private void exitButton_Click( object sender, EventArgs e )

132 {

133 // determine whether file exists

134 if ( output != null )

135 {

136 // close file

137 try

138 {

139 output.Close(); // close FileStream

140 } // end try

141 // notify user of error closing file

142 catch ( IOException )

143 {

144 MessageBox.Show( "Cannot close file", "Error",

145 MessageBoxButtons.OK, MessageBoxIcon.Error );

146 } // end catch

147 } // end if

Outline

CreateFileForm.cs

(7 of 11 )

148

149 Application.Exit();

150 } // end method exitButton_Click

151 } // end class CreateFileForm

152 } // end namespace CreateFile

Page 95: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

95Outline

CreateFileForm.cs

(8 of 11 )

a) a user starts by clicking on the “Save As” button (as before for text files)

b) the “Save As” file dialog window (shown below) appears, so the user can select directory and type in file name.

SaveFileDialog

Files and directories

Type in file name

Page 96: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

96Outline

CreateFileForm.cs

(9 of 11 )

c) Account 100, “Nancy Brown”, saved with a balance of -25.54

d) Account 200, “Stacey Dunn”, saved with a balance of 314.33

f) Account 400, “Dave Smith”, saved with a balance of 258.34

e) Account 399, “Doug Barker”, saved with a balance of 0

Page 97: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

97Outline

CreateFileForm.cs

(10 of 11 )

g) Account 500, “Sam Stone”, saved with a balance of 34.98

h) Once all accounts are saved, the Exit button closes the application

IMPORTANT:

• Remember that binary files (e.g, created by object serialization) are not human readable

• In contrast, text files (used before, in Sec. 19.5 – 19.6) are human readable

Page 98: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

98Outline

CreateFileForm.cs

(11 of 11 )

READ LATER

Common Programming Error 19.2It is a logic error to open an existing file foroutput when the user wishes to preserve the file. The original file’s contents will be lost.

• Method Serialize takes the FileStream object as the first argument so that the BinaryFormatter can write its second argument to the correct file.

Page 99: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

99

1 // Fig. 19.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; //allows using BankUIForm and RecorSerializable

9

10 namespace ReadSequentialAccessFile

11 {

12 public partial class ReadSequentialAccessFileForm : BankUIForm

13 {

14 // object for deserializing Record in binary format

15 private BinaryFormatter reader = new BinaryFormatter();

16 private FileStream input; // stream for reading from a file

17

• Read and display the contents of the binary file created by the previous program (which serialized & wrote objects into a binary file)

Outline

ReadSequentialAccessFileForm.cs

(1 of 8 )

Create the BinaryFormatter that will be used to deserialize read objects.

19.10 Reading and Deserializing Datafrom a Binary File

Page 100: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

10018 // parameterless constructor

19 public ReadSequentialAccessFileForm()

20 {

21 InitializeComponent();

22 } // end constructor

23

24 // invoked when user clicks the Open button

25 private void openButton_Click( object sender, EventArgs e )

26 {

27 // create and show dialog box enabling user to open file

28 DialogResult result; // result of OpenFileDialog

29 string fileName; // name of file containing data

30

31 using ( OpenFileDialog fileChooser = new OpenFileDialog() )

32 {

33 result = fileChooser.ShowDialog();

34 fileName = fileChooser.FileName; // get specified name

35 } // end using

36

Outline

ReadSequentialAccessFileForm.cs

(2 of 8 )

As before for text files, a user starts by clicking on “Open File” above.

Window shown below appears then, so the user can select directory and file.

Page 101: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

10137 // ensure that user clicked "OK" (that is, “Open”, not “Cancel”)

38 if ( result == DialogResult.OK )

39 {

40 ClearTextBoxes(); // A method from BankUIForm

41

42 // show error if user specified invalid file

43 if ( fileName == string.Empty )

44 MessageBox.Show( "Invalid File Name", "Error",

45 MessageBoxButtons.OK, MessageBoxIcon.Error );

46 else

47 {

48 // create FileStream to obtain read access to file

49 input = new FileStream(

50 fileName, FileMode.Open, FileAccess.Read );

51

52 openButton.Enabled = false; // disable Open File button

53 nextButton.Enabled = true; // enable Next Record button

54 } // end else

55 } // end if

56 } // end method openButton_Click

57

Outline

ReadSequentialAccessFileForm.cs

(3 of 8 )

Open the file for input by creating a FileStream object.

Page 102: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

102

58 // invoked when user clicks Next button

59 private void nextButton_Click( object sender, EventArgs e )

60 {

61 // deserialize Record and store data in TextBoxes

62 try

63 {

64 // get next RecordSerializable available in file

65 RecordSerializable record =

66 ( RecordSerializable ) reader.Deserialize( input );

67

68 // store Record values in temporary string array

69 string[] values = new string[] {

70 record.Account.ToString(),

71 record.FirstName.ToString(),

72 record.LastName.ToString(),

73 record.Balance.ToString()

74 };

75

76 // copy string-array values to TextBox values

77 SetTextBoxValues( values );

78 } // end try

Outline

ReadSequentialAccessFileForm.cs

(4 of 8 )

We use method Deserialize (of the BinaryFormatter) to read the data.

Page 103: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

10379 // handle exception when there are no Records in file

80 catch ( SerializationException )

81 {

82 input.Close(); // close FileStream if no Records in file

83 openButton.Enabled = true; // enable Open File button

84 nextButton.Enabled = false; // disable Next Record button

85

86 ClearTextBoxes();

87

88 // notify user if no Records in file

89 MessageBox.Show( "No more records in file", string.Empty,

90 MessageBoxButtons.OK, MessageBoxIcon.Information );

91 } // end catch

92 } // end method nextButton_Click

93 } // end class ReadSequentialAccessFileForm

94 } // end namespace ReadSequentialAccessFile

Outline

ReadSequentialAccessFileForm.cs

(5 of 8 )

Page 104: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

104Outline

ReadSequentialAccessFileForm.cs

(6 of 8 )

a) a user starts by clicking on the “Open File” button (as before for text files)

b) the “Open” file dialog window (shown below) appears, so the user can select directory and file name.

Page 105: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

105Outline

ReadSequentialAccessFileForm.cs

(7 of 8 )

c) User clicks on “Next Record”

to read account 100

e) User clicks on “Next Record”

to read account 399

f) User clicks on “Next Record”

to read account 400

d) User clicks on “Next Record”

to read account 200

Page 106: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

106Outline

ReadSequentialAccessFileForm.cs

(8 of 8 )

g) User clicks on “Next Record”

to read account 500

h) User clicks again and is shown a

messagebox when all records have

been read

• Things to remember:

• Deserialize returns a reference of type object

• If an error occurs during deserialization, a SerializationException is thrown

(not “DeserializationException”).

Page 107: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

107

IMPORTANT NOTE:

There is another type of files: Random-Access Files

Edition 1 of this textbook included:

17.7 Random-Access Files

17.8 Creating a Random-Access File

17.9 Writing Data Randomly to a Random-Access File

17.10 Reading Data Sequentially from a Random-Access File

17.11 Case Study: A Transaction-Processing Program

Page 108: 2009 Pearson Education, Inc. All rights reserved. 1 Ch.19 Files and Streams Many slides modified by Prof. L. Lilien (even many without explicit message)

2009 Pearson Education, Inc. All rights reserved.

108

The End of Ch.19 (Files & Streams)