Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Similar documents
Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

05/31/2009. Data Files

C# Continued. Learning Objectives:

C# Continued. Learning Objectives:

How to read/write text file

C# Data Manipulation

File Handling Programming 1 C# Programming. Rob Miles

Introduction to Programming Using Java (98-388)

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later

C# Data Manipulation

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Console.ReadLine(); }//Main

Industrial Programming

1. A Web Form created in Visual Basic can only be displayed in Internet Explorer. True False

C# 2008 and.net Programming for Electronic Engineers - Elektor - ISBN

CHAPTER 1: INTRODUCTION TO THE IDE 3

CHAPTER 1: INTRODUCING C# 3

ENGR/CS 101 CS Session Lecture 13

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads

Data Structures. 03 Streams & File I/O

Chapter 6 Introduction to Defining Classes

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

CIS Intro to Programming in C#

IST311 Chapter13.NET Files (Part2)

Microsoft Visual Basic 2005: Reloaded

Object-Oriented Programming

Short Notes of CS201

Chapter 1 Getting Started

CS201 - Introduction to Programming Glossary By

Unit 4 Advanced Features of VB.Net

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

James Foxall. Sams Teach Yourself. Visual Basic 2012 *24. Hours. sams. 800 East 96th Street, Indianapolis, Indiana, USA

IT 374 C# and Applications/ IT695 C# Data Structures

Darshan Institute of Engineering & Technology for Diploma Studies

Computer measurement and control

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

abstract binary class composition diamond Error Exception executable extends friend generic hash implementation implements

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Making Decisions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Chapter 14: Files and Streams

Menus and Printing. Menus. A focal point of most Windows applications

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array?

Course Hours

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Learning to Program in Visual Basic 2005 Table of Contents

CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

15CS45 : OBJECT ORIENTED CONCEPTS

Programming overview

Chapter 1: Object-Oriented Programming Using C++

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

C# Programming for Developers Course Labs Contents

Index COPYRIGHTED MATERIAL

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Konark - Writing a KONARK Sample Application

Microsoft. Microsoft Visual C# Step by Step. John Sharp

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

CS260 Intro to Java & Android 03.Java Language Basics

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Mastering VB.NET using Visual Studio 2010 Course Length: 5 days Price: $2,500

Java: introduction to object-oriented features

Motivations. Chapter 12 Exceptions and File Input/Output

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Table of Contents. 1 Context 2. 2 Problem statement 2. 3 Related work 2

Oops known as object-oriented programming language system is the main feature of C# which further support the major features of oops including:

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

BBM 102 Introduction to Programming II Spring Exceptions

JDirectoryChooser Documentation

Brief Summary of Java

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Cpt S 122 Data Structures. Introduction to C++ Part II

Java Programming Training for Experienced Programmers (5 Days)

6.Introducing Classes 9. Exceptions

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Programming for the Web with PHP

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Image Data Binding. Save images in database An image needs large amount of storage space. Only binary variable length fields may hold images.

Murach s Beginning Java with Eclipse

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

UNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net

Starting Out with Java: From Control Structures Through Objects Sixth Edition

A Short Summary of Javali

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Interview Questions of C++

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

C# Programming: From Problem Analysis to Program Design. Fourth Edition

Programming in Visual Basic with Microsoft Visual Studio 2010

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

Introduction Unit 4: Input, output and exceptions

BBM 102 Introduction to Programming II Spring 2017

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Get Unique study materials from

Transcription:

12 Working with Files C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies 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 1

Chapter Objectives (continued) Read data from text files Write data to text files Explore appending data to text files Use the FileDialog Class 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 2

System.IO Namespace (continued) System.IO Namespace (continued) Many are exception classes that can be thrown while accessing information using streams, files and directories 3

System.IO Namespace (continued) Figure 12-1.NET file class hierarchy 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 ); 4

File Class File Class (continued) Visual Studio intellisense feature provides information Figure 12-2 IntelliSense display 5

File Class (continued) One static method of the File class is Exists( ) Example 12-11 /* 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)) 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 6

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 ) ); GetAttributes( ) returns enumeration Figure 12-3 Output from the DirectoryStructure application Directory Class Static methods for creating and moving through directories and subdirectories 7

Directory Class (continued) 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 8

17 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: \n0}\n", Directory.GetCurrentDirectory( )); 9

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 File Streams (continued) 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; 10

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 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( ); 11

File Streams (continued) File Streams (continued) 12

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 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 t clause Form closing event closes the file and releases resources associated with file Also enclosed in a try catch clause 13

Writing Text Files (continued) using System.IO; private StreamWriter fil; object : // more statements needed try fil = new StreamWriter( saying.txt ); } : // more statements t t needed d try } // Added for file access //Declares a file Instantiate stream StreamWriter object fil.writeline(this.txtbxsaying.text); this.txtbxsaying.text = ; Retrieve value from text box; write it to the file 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) 14

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 Retrieve values from file; place infile = new StreamReader( name.txt ); them in a while ((invalue = infile.readline())!= null) ListBox this.lstboxnames.items.add(invalue); } Reading Text Files FileAccessApp Application Read from text files in sequential fashion Figure 12-8 Content of name.txt file Figure 12-9 Output 15

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 try Adding a Using Statement (continued) using (StreamReader infile = new StreamReader("name.txt")) while ((invalue = infile.readline())!= null) this.lstboxnames.items.add(invalue); ltb l } } 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 32 16

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 runtime OpenFileDialog and CloseFileDialog classes Classes are derived from the FileDialog class FileDialog is an abstract class 33 FileDialog Class (continued) FileName property is used by OpenFileDialog l and CloseFileDialog l l 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 17

FileDialog Class (continued) Figure 12-13 Placing OpenFileDialog and SaveFileDialog controls 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 t at SreamReader infile = new StreamReader(openFileDialog1.FileName); 18

FileDialog Class (continued) Figure 12-14 ShowDialog( ) method executed 19