Docsity

Working - Advanced Programming - Lecture Notes, Study notes of Advanced Computer Programming

Toggle sidebar
bg1
C# Programming: From Problem Analysis to Program Design, 3rd ed. 13-1
Chapter 13
Working with Files
At a Glance
Instructor’s Manual Table of Contents
♦ Chapter Overview
♦ Chapter Objectives
♦ Instructor Notes
♦ Quick Quizzes
♦ Discussion Questions
♦ Projects to Assign
♦ Key Terms
Docsity.com
pf3
pf4
pf5

Partial preview of the text

Download Working - Advanced Programming - Lecture Notes and more Study notes Advanced Computer Programming in PDF only on Docsity!

Chapter 13

Working with Files

At a Glance

Instructor’s Manual Table of Contents

♦ Chapter Overview

♦ Chapter Objectives

♦ Instructor Notes

♦ Quick Quizzes

♦ Discussion Questions

♦ Projects to Assign

♦ Key Terms

Lecture Notes

Chapter Overview

The chapter introduces students to dealing with data sources other than the keyboard. The major classes used to work with file and directory structures are examined. Programs that access and store data in text and binary files are explored.

Chapter Objectives

In this chapter, students will:

  • Learn about the System.IO namespace
  • Explore the File and Directory classes
  • Contrast the FileInfo and DirectoryInfo classes to the File and Directory classes
  • Discover how stream classes are used
  • Read data from text files
  • Write data to text files
  • Explore appending data to text files
  • Use exception-handling techniques to process text files
  • Read from and write to binary files

Instructor Notes

SYSTEM.IO NAMESPACE

System.IO namespace provides basic file and directory support classes. It also contains types that enable you to read and write files and data streams. Many of the System.IO types are exception classes. Others deal with creating and accessing file stream objects. Four of the classes provide methods for the copying, deletion, moving, and opening of files and directories.

FILE AND DIRECTORY CLASSES

The File, FileInfo, Directory, and DirectoryInfo classes are utility classes that work with stream objects allowing you to manipulate files and directory structures. The File and Directory classes expose only static members.

File Class File class exposes only static members that aid in the copying, moving, renaming, creating, opening, deleting, and appending to files. One of the static methods of the File class is Exists(). Prior to writing program statements that access data in a file, you should always check to make sure the file is available.

FILE STREAMS

Streams represent a chunk of data and provide a way to work with a sequence of bytes. Defined in the System.IO namespace are several abstract classes, including Stream, TextReader, and TextWriter. Both the TextReader and TextWriter facilitate working with data in a text (readable) format. Examples in this chapter illustrate using StreamReader and StreamWriter classes, which are derived from the TextReader and TextWriter classes.

The StreamWriter class has implementations for Write( ) and WriteLine( ) methods similar to the Console class methods. StreamReader includes implementations of Read( ) and ReadLine( ). The simplest constructor for these classes includes a single argument for the name of the file. The name may include the full path indicating where the file is located. The following are statements that construct objects of the StreamWriter and StreamReader classes: StreamWriter outputFile = new StreamWriter(“someOutputFileName”); StreamReader inputFile = new StreamReader(“someInputFileName”);

Add a using directive for the System.IO namespace to avoid fully qualifying the StreamReader identifier. You can then use the Write( ) and WriteLine( ) methods with the instantiated stream object, and the characters are written to the file as opposed to the monitor. The values are stored in the file as text characters: string objects. ReadLine( ) reads a line of characters and returns the data as a string.

Writing Text Files You should enclose all file access inside try…catch blocks. When you write characters to a file using the StreamWriter class, values are placed in the file in a sequential fashion.

After the file is created, the Close( ) method is used to finish storing the values. In Visual Studio, when you create a file (or attempt to access one), if a path is not specified for the filename, the bin\Debug subdirectory for the current project is used. If an invalid path is listed in the constructor for the StreamWriter object, an IOException exception is thrown.

Reading Text Files Using members of the StreamReader class, accessing the contents of a text file is as easy as creating it. Values are read from text files in sequential fashion. The ReadLine( ) method is used with the infile object to retrieve one line of text from the file. It can be placed in a loop to retrieve all values. One way to do this is as follows: while ((inValue = inFile.ReadLine( )) != null)

Adding a Using Statement The using keyword has two major uses. The using keyword can be used to define a scope for an object and have the CLR automatically release the resource when the object goes out of scope. This is extremely useful when working with files or databases.

You can instantiate a StreamReader or StreamWriter object inside a using block. The using statement can occur inside a try clause. Once the file stream object is instantiated in the using block, you are guaranteed that the file is closed when you exit the block. You no longer need to call the Close( ) method.

Random Access The FileStream class also supports randomly accessing data. Values can be processed in any order. Seek( ) lets you move the read or write position to any location within the stream using an offset reference parameter.

Quick Quiz

  1. The Stream class used to retrieve values from a file is ________________. Answer: StreamReader
  2. True or False: The ReadLine( ) method retrieves the entire file into memory for processing. Answer: False
  3. A(n) _____________ exception is thrown if the file is not found. Answer: IOException
  4. How does the program indicate the name of the file to access? Answer: The filename is sent as an argument to the constructor.

BINARYREADER AND BINARYWRITER CLASSES

These classes are used for writing and reading binary data. The files created are readable by the computer, but unlike the files created by the StreamWriter class, you cannot simply open and read the contents of a binary file using Notepad. A program is needed to interpret the contents of the file.

In addition to constructors, the BinaryReader and BinaryWriter classes expose a number of instance methods. The BinaryWriter class has Close( ), Flush( ), Seek( ), and Write( ) methods. The reader class has, in addition to close, PeekChar( ), Read( ), and a number of type-specific read methods (ReadBoolean( ), ReadByte( ), ReadChar( ), ReadDecimal( ), ReadDouble( ), ReadInt32( ), and ReadString( )).

Other Stream Classes Objects of streams can be wrapped with an object of the BufferedStream class, enabling buffering of characters. This can improve the speed and performance of file-handling operations.

Other stream classes include NetworkStream, which provides methods for sending and receiving data over stream Sockets. NetworkStream has methods similar to the other stream classes, including Read and Write methods. The FileStream class supports randomly accessing data in a file.

FileDialog Class Instead of hard coding the filenames and paths, you can add dialog boxes to allow the user to enter names and paths at run time. OpenFileDialog class is used to access a file for input;

CODING STANDARDS

Encourage students to include exception-handling techniques to deal with file or directory not found types of problems.

Discussion Questions

Some interesting topics of discussion in this chapter include:

  • What advantages would the FileInfo class offer over the File class?
  • Why store data in a binary file if the data is unreadable without a special program?
  • Describe a situation in which an enumeration might make your program code more readable.

Projects to Assign

All of the Multiple Choice Exercises, Problems 1- Odd-numbered Short Answer Exercises, Problems 21 - 25 Programming Exercises, Problems 2, 6, 8, and 9

Key Terms

¾ enumeration : special form of value type that supplies alternate names for the values of an underlying primitive type ¾ stream : representation of a chunk of data that provides a way to work with a sequence of bytes