43
Chapter 12 Chapter 12 Working with Files Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

Embed Size (px)

Citation preview

Page 1: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

Chapter 12Chapter 12Working with FilesWorking with Files

CIS 3260Introduction to Programming using C#Hiro Takeda

Page 2: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

2

Chapter ObjectivesChapter ObjectivesLearn about the System.IO

namespaceExplore the File and Directory

classesContrast the FileInfo and

DirectoryInfo classes to the File and Directory classes

Discover how stream classes are used

Read data from text files

Page 3: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

3

Chapter Objectives Chapter Objectives ((continuedcontinued))Write data to text filesExplore appending data to text

filesUse exception-handling

techniques to process text filesRead from and write to binary

files

Page 4: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

4

System.IO NamespaceSystem.IO NamespaceProvides basic file and directory

support classesContains types that enable you to

read and write files and data streams

Many of the types or classes defined as part of the System.IO namespace are designed around streams

Page 5: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

5

System.IO Namespace System.IO Namespace ((continuedcontinued))

Page 6: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

6

System.IO Namespace System.IO Namespace ((continuedcontinued))

Many are exception

classes that can be thrown while

accessing information

using streams, files and

directories

Page 7: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

7

System.IO Namespace System.IO Namespace ((continuedcontinued))

Figure 12-1 .NET file class hierarchy

Page 8: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

8

File and Directory ClassesFile and Directory ClassesUtility classes allow you to manipulate

files and directory structures ◦Aid in copying, moving, renaming, creating,

opening, deleting, and appending files Expose only static members

◦Objects are not instantiated from these classes

◦To invoke the method, the method name is preceded by the class name (as opposed to an object’s name)

File.Copy(“sourceFile”, “targetFile”);

Page 9: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

9

File ClassFile Class

Page 10: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

10

File Class (File Class (continuedcontinued))Visual Studio intelliSense feature

provides information

Figure 12-2 IntelliSense display

Page 11: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

11

File Class (File Class (continuedcontinued))

One static method of the File class is Exists( )

Example 12-1/* DirectoryStructure.cs illustrates using File and Directory

utilities. */using System;using System.IO;class DirectoryStructure{ public static void Main( ) { string fileName = "BirdOfParadise.jpg"; if (File.Exists(fileName)) {

Page 12: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

12

File Class (File Class (continuedcontinued))GetAttritubes( ) returns a

FileAttributes enumerationEnumeration is a special form of

value type that supplies alternate names for the values of an underlying primitive type◦Enumeration type has a name, an

underlying type, and a set of fields

Page 13: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

13

File Class (File Class (continuedcontinued))Console.WriteLine( "FileName: {0}", fileName );

Console.WriteLine( "Attributes: {0}", File.GetAttributes(fileName) );

Console.WriteLine( "Created: {0}", File.GetCreationTime( fileName ) );

Console.WriteLine( "Last Accessed: {0}",File.GetLastAccessTime

( fileName ) );

Figure 12-3 Output from the DirectoryStructure application

GetAttributes( ) returns

enumeration

Page 14: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

14

Directory ClassDirectory ClassStatic methods for creating and

moving through directories and subdirectories

Page 15: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

15

Directory Class (Directory Class (continuedcontinued))

Page 16: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

16

DirectoryInfo and FileInfo DirectoryInfo and FileInfo ClassesClassesAdd additional functionality

beyond File and Directory classes ◦Difference – Both have instance

methods instead of static members ◦Both have public properties and public

constructors◦Neither can be inherited

Page 17: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

17

Page 18: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

18

DirectoryInfoDirectoryInfoAdds two other key properties,

Parent and Root◦Parent gets the parent directory of a

specified subdirectory◦Root gets the root portion of a path ◦Be careful with paths; they must be well-

formed or an exception is raised

DirectoryInfo dir = new DirectoryInfo(".");

Console.WriteLine("Current Directory: \n{0}\n",Directory.GetCurrentDirectory( ));

Page 19: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

19

File StreamsFile StreamsSeveral abstract classes for dealing with

files Stream, TextWriter, and TextReader

Stream classes provide generic methods for dealing with input/output◦ IO.Stream class and its subclasses – byte-level

data

◦ IO.TextWriter and IO.TextReader – data in a text (readable) format StreamReader and StreamWriter derived classes of

IO.TextWriter and IO.TextReader

Page 20: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

20

File Streams (File Streams (continuedcontinued))StreamWriter class for write data to text file

◦ Includes implementations for Write( ) and WriteLine( )

StreamReader class to read or and from text files

◦ Includes implementations of Read( ) and ReadLine( )

System.IO namespace

◦Using System.IO;

Page 21: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

21

File Streams (File Streams (continuedcontinued))StreamWriter outputFile = new

StreamWriter("someOutputFileName");StreamReader inputFile = new

StreamReader("someInputFileName");

outputFile and inputFile represent the file stream objects

Actual file names are “someOutputFileName” and “someInputFileName” – inside double quotes◦Place file extensions such as .dat, .dta, or .txt

onto the end of actual filename when it is created

Page 22: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

22

File Streams (File Streams (continuedcontinued))

Use Write( ) or WriteLine( ) with the instantiated stream object

outputFile.WriteLine("This is the first line in a text file");

Use Read( ) or ReadLine( ) with the instantiated stream object

string inValue = inputFile.ReadLine( );

Page 23: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

23

File Streams (File Streams (continuedcontinued))

Page 24: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

24

File Streams (File Streams (continuedcontinued))

Page 25: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

25

Writing Text FilesWriting Text FilesEnclosed attempts to access text files

inside try…catch blocks

Constructor for StreamWriter class is overloaded

◦To Append data onto the end of the file, use the constructor with Boolean variable

fileOut = new StreamWriter(“../../info.txt”, true);

true indicates to append

Values are placed in the file in a sequential fashion

Page 26: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

26

Writing Text Files – SayingGUI Writing Text Files – SayingGUI ApplicationApplicationThree event-handler methods included

◦Form-load event handler, an object of the StreamWriter class is instantiated   Included in a try…catch clause

◦Button click event-handler method retrieves the string from the text box and writes the text to the file Also enclosed in a try…catch clause

◦Form closing event closes the file and releases resources associated with file Also enclosed in a try…catch clause

Page 27: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

27

Writing Text Files (Writing Text Files (continuedcontinued))using System.IO; // Added for file accessprivate StreamWriter fil; //Declares a file stream

object: // more statements needed

try{

fil = new StreamWriter(“saying.txt”);}

: // more statements neededtry{

fil.WriteLine(this.txtBxSaying.Text);this.txtBxSaying.Text =“”;

}

Retrieve value from

text box; write it to the file

Instantiate StreamWriter

object

Page 28: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

28

Writing Text Files – SayingGUI Writing Text Files – SayingGUI Application (Application (continuedcontinued))

If a path is not

specified for the file

name, the bin\debug

subdirectory for the current

project is used

Figure 12-7 DirectoryNotFoundException thrown

Page 29: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

29

Reading Text Files Reading Text Files StreamReader class enables lines of text to

be read from a file Constructor for StreamReader is overloaded

◦Can specify different encoding schema or an initial buffer size

Can use members of parent or ancestor classes or static members of the File class ◦To avoid programming catch for

FileNotFoundException or DirectoryNotFoundException, call File.Exists(filename)

Page 30: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

30

Reading Text Files Reading Text Files ((continuedcontinued))using System.IO; // Added for file access

private StreamReader inFile; // Declares a file stream object

: // more statements needed

if (File.Exists(“name.txt”))

{

try

{

inFile = new StreamReader(“name.txt”);

while ((inValue = inFile.ReadLine()) != null)

{

this.lstBoxNames.Items.Add(inValue);

}

Retrieve values from file; place

them in a ListBox

Page 31: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

31

Reading Text FilesReading Text Files –FileAccessApp –FileAccessApp ApplicationApplication

Read from text files in sequential fashion

Figure 12-8 Content of name.txt file Figure 12-9 Output

Page 32: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

32

Adding a Using StatementAdding a Using StatementDefine a scope for an object with the

using keyword◦CLR automatically disposes of, or releases,

the resource when the object goes out of scope

◦Useful when working with files or databases When writing data to a file, the data is not

stored in the file properly until the file is closed Fail to close the file – you will find an empty file With using block, not necessary for you to call the

Close( ) method – automatically called by the CLR

Page 33: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

33

Adding a Using Statement Adding a Using Statement ((continuedcontinued))

try { using (StreamReader inFile = new

StreamReader("name.txt")) { while ((inValue =

inFile.ReadLine()) != null) {

this.lstBoxNames.Items.Add(inValue); } }

StreamReader object is defined and instantiated inside the using block

By instantiating the inFile object here, the object exists only in this block

You are guaranteed the file is closed when you exit the block

Page 34: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

34

BinaryReader and BinaryWriter BinaryReader and BinaryWriter ClassesClassesFiles created are readable by the

computer ◦You cannot open and read binary file

using Notepad

Page 35: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

35

Page 36: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

36

Other Stream ClassesOther Stream ClassesNetworkStream class provides

methods for sending and receiving data over stream sockets ◦Methods similar to the other stream

classes, including Read and Write methods MemoryStream class used to create

streams that have memory as a backing store instead of a disk or a network connection◦Reduce the need for temporary buffers

and files in an application

Page 37: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

37

FileDialog ClassFileDialog ClassEnables browsing to a specific location

to store or retrieve files ◦Displays Open file dialog box to allow user

to traverse to the directory where the file is located and select file

◦Displays a Save As dialog box to allow user to type or select filename at runtime

OpenFileDialog and CloseFileDialog classes ◦Classes are derived from the FileDialog class◦FileDialog is an abstract class

Page 38: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

38

FileDialog Class (FileDialog Class (continuedcontinued))FileName property is used by

OpenFileDialog and CloseFileDialog ◦Set or get the name of the file from the

dialog box Drag the OpenFileDialog and/or

the CloseFileDialog control from the toolbox onto your form ◦ Placed in the component tray

Page 39: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

39

FileDialog Class (FileDialog Class (continuedcontinued))

Figure 12-13 Placing OpenFileDialog and SaveFileDialog controls

Page 40: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

40

FileDialog Class (FileDialog Class (continuedcontinued))ShowDialog( ) method used to cause the

dialog boxes to appear openFileDialog1.ShowDialog( ); orsaveFileDialog1.ShowDialog( );

To retrieve the filename from the textbox in the dialog box, use the FileName property

Retrieved value can be used as the argument for the stream object instantiation

SreamReader inFile = new StreamReader(openFileDialog1.FileName);

Page 41: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

41

FileDialog Class (FileDialog Class (continuedcontinued))

Figure 12-14 ShowDialog( ) method executed

Page 42: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

42

ICW WaterDepth File App ICW WaterDepth File App Example Example Graphical user interface solution

was designed for application in Chapter 11◦Review the problem specification in

Figure 11-21Modified to allow the results to

be captured and stored for future use◦Data stored in a text file

Figure 12-15 Data file prototype

Page 43: Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda

43

Figure 12-16 Values stored in a text file