C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 11 MORE WINDOWS CONTROLS & STANDARD DIALOG BOXES.
Advertisements

C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Chapter 12: Using ADO.NET 2.0 Programming with Microsoft Visual Basic 2005, Third Edition.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Programming Based on Events
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Advanced Object-Oriented Programming Features
Using Multiple Forms. Creating a New Form ProjectAdd Windows Form.
ASP.NET Programming with C# and SQL Server First Edition
C# Programming: From Problem Analysis to Program Design1 Introduction to Windows Programming C# Programming: From Problem Analysis to Program Design 3.
Chapter 3 Introduction to Event Handling and Windows Forms Applications.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
A First Program Using C#
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Visual C Sharp – File I/O - 1 Variables and arrays only temporary - lost when a program terminates Files used for long term storage (Data bases considered.
Chapter 12 Working with Files CIS 3260 Introduction to Programming using C# Hiro Takeda.
Neal Stublen Open/Close Connections  ADO.NET uses “connection pooling” to optimize opening and closing connections to the database.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Chapter 8: Writing Graphical User Interfaces
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
Chapter 5 Menus, Common Dialog Boxes, and Methods Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
File I/O 11_file_processing.ppt
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
Chapter 6 OOP: Creating Object-Oriented Programs Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Ajay Tripathi Input Output. Ajay Tripathi Input/output (IO) refers to the operations for reading and writing data to streams and files. In the.NET Framework,
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Introduction to Object-oriented Programming
INF230 Basics in C# Programming
Creating Your Own Classes
C# Programming: From Problem Analysis to Program Design
Files.
18 Files and Streams.
Using Multiple Forms.
Files and Streams.
C# Programming: From Problem Analysis to Program Design
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
File Input/Output (I/O)
VISUAL BASIC.
Topics Introduction to File Input and Output
Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline Test-Driving the Microwave Oven Application Designing.
CIS16 Application Development Programming with Visual Basic
Files & Streams.
Files and Streams Lect10 GC201 12/1/2015.
CIS16 Application Development and Programming using Visual Basic.net
Files and Streams.
Topics Introduction to File Input and Output
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13

C# Programming: From Problem Analysis to Program Design2 Chapter Objectives 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

C# Programming: From Problem Analysis to Program Design3 Chapter Objectives ( continued ) 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

C# Programming: From Problem Analysis to Program Design4 System.IO Namespace Provides basic file and directory support classes Contains 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

C# Programming: From Problem Analysis to Program Design5 System.IO Namespace ( continued )

C# Programming: From Problem Analysis to Program Design6 System.IO Namespace ( continued ) Many are exception classes that can be thrown while accessing information using streams, files, and directories

C# Programming: From Problem Analysis to Program Design7 System.IO Namespace ( continued ) Figure 13-1.NET file class hierarchy

C# Programming: From Problem Analysis to Program Design8 File and Directory Classes Utility 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”);

C# Programming: From Problem Analysis to Program Design9 File Class

C# Programming: From Problem Analysis to Program Design10 File Class ( continued ) Visual Studio IntelliSense feature provides information Figure 13-2 IntelliSense display

C# Programming: From Problem Analysis to Program Design11 File Class ( continued ) One static method of the File class is Exists( ) Example 13-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)) {

C# Programming: From Problem Analysis to Program Design12 File Class ( continued ) GetAttritubes( ) returns a FileAttributes enumeration Enumeration 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

C# Programming: From Problem Analysis to Program Design13 File Class ( continued ) 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 13-3 Output from the DirectoryStructure application GetAttributes( ) returns enumeration

C# Programming: From Problem Analysis to Program Design14 Directory Class Static methods for creating and moving through directories and subdirectories

C# Programming: From Problem Analysis to Program Design15 Directory Class ( continued )

C# Programming: From Problem Analysis to Program Design16 DirectoryInfo and FileInfo Classes Add 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

C# Programming: From Problem Analysis to Program Design17

C# Programming: From Problem Analysis to Program Design18 DirectoryInfo Adds 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( ));

C# Programming: From Problem Analysis to Program Design19 File Streams Several 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

C# Programming: From Problem Analysis to Program Design20 File Streams ( continued ) StreamWriter class for writing data to text file –Includes implementations for Write( ) and WriteLine( ) StreamReader class to read or write to or from text files –Includes implementations of Read( ) and ReadLine( ) System.IO namespace –Using System.IO;

C# Programming: From Problem Analysis to Program Design21 File Streams ( continued ) 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

C# Programming: From Problem Analysis to Program Design22 File Streams ( continued ) 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( );

C# Programming: From Problem Analysis to Program Design23 File Streams ( continued )

C# Programming: From Problem Analysis to Program Design24 File Streams ( continued )

C# Programming: From Problem Analysis to Program Design25 Writing Text Files Enclosed 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

C# Programming: From Problem Analysis to Program Design26 Writing Text Files – SayingGUI Application Three 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

C# Programming: From Problem Analysis to Program Design27 Writing Text Files ( continued ) using System.IO; // Added for file access private StreamWriter fil; //Declares a file stream object : // more statements needed try { fil = new StreamWriter(“saying.txt”); } : // more statements needed try { fil.WriteLine(this.txtBxSaying.Text); this.txtBxSaying.Text =“”; } Retrieve value from text box; write it to the file Instantiate StreamWriter object

C# Programming: From Problem Analysis to Program Design28 Writing Text Files – SayingGUI Application ( continued ) If a path is not specified for the filename, the bin\debug subdirectory for the current project is used Figure 13-7 DirectoryNotFoundException thrown

C# Programming: From Problem Analysis to Program Design29 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)

C# Programming: From Problem Analysis to Program Design30 Reading Text Files ( continued ) 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

C# Programming: From Problem Analysis to Program Design31 Reading Text Files – FileAccessApp Application Read from text files in sequential fashion Figure 13-8 Content of name.txt file Figure 13-9 Output

C# Programming: From Problem Analysis to Program Design32 Adding a Using Statement Define 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

C# Programming: From Problem Analysis to Program Design33 Adding a Using Statement ( continued ) 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

C# Programming: From Problem Analysis to Program Design34 BinaryReader and BinaryWriter Classes Files created are readable by the computer –You cannot open and read binary file using Notepad

C# Programming: From Problem Analysis to Program Design35

C# Programming: From Problem Analysis to Program Design36

C# Programming: From Problem Analysis to Program Design37 Other Stream Classes NetworkStream 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

C# Programming: From Problem Analysis to Program Design38 FileDialog Class Enables 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 run time OpenFileDialog and CloseFileDialog classes –Classes are derived from the FileDialog class –FileDialog is an abstract class

C# Programming: From Problem Analysis to Program Design39 FileDialog Class ( continued ) 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

C# Programming: From Problem Analysis to Program Design40 FileDialog Class ( continued ) Figure Placing OpenFileDialog and SaveFileDialog controls

C# Programming: From Problem Analysis to Program Design41 FileDialog Class ( continued ) ShowDialog( ) method used to cause the dialog boxes to appear openFileDialog1.ShowDialog( ); or saveFileDialog1.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);

C# Programming: From Problem Analysis to Program Design42 FileDialog Class ( continued ) Figure ShowDialog( ) method executed

C# Programming: From Problem Analysis to Program Design43 ICW WaterDepth File App Example Graphical user interface solution was designed for application in Chapter 12 –Review the problem specification in Figure Modified to allow the results to be captured and stored for future use –Data stored in a text file Figure Data file prototype

C# Programming: From Problem Analysis to Program Design44 Figure Values stored in a text file ICW WaterDepth File App Example

Coding Standards Good style improves the maintainability of the software Include exception-handling techniques to deal with file or directory not found types of problems Always close files that are opened in applications C# Programming: From Problem Analysis to Program Design45

C# Programming: From Problem Analysis to Program Design46 Chapter Summary System.IO namespace File and Directory classes –Static members –Copy, move, append to, and rename files –Create, delete, and rename directories FileInfo and DirectoryInfo classes –Added functionality to File and Directory classes –Instantiate objects of these classes

C# Programming: From Problem Analysis to Program Design47 Chapter Summary ( continued ) StreamReader StreamWriter BinaryReader and BinaryWriter classes –Create and access binary (non-readable) files FileDialog –OpenFileDialog –CloseFileDialog –ShowDialog used to display dialog box