Input and Output 23: Input and Output

Slides:



Advertisements
Similar presentations
Reading and Writing Text Files Svetlin Nakov Telerik Corporation
Advertisements

Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
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.
File Systems Files and directories Absolute and relative names Text and binary files Sequential-access and random-access files.
7. The FCL: files, databases, & data structures. 2 Microsoft Objectives “The Framework Class Library (FCL) contains thousands of classes, from graphics.
C# Programming: From Problem Analysis to Program Design1 Working with Files C# Programming: From Problem Analysis to Program Design 3 rd Edition 13.
File and Streams There are many ways of organizing records in a file. There are many ways of organizing records in a file. The most common type of organization.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Understanding Input/Output (I/O) Classes Lesson 5.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Computer and Programming File I/O File Input/Output Author: Chaiporn Jaikaeo, Jittat Fakcharoenphol Edited by Supaporn Erjongmanee Lecture 13.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
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.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
 2006 Pearson Education, Inc. All rights reserved Files and Streams.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Streams & File Input/Output Basics C#.Net Development Version 1.1.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Files and Streams File Types, Using Streams, Manipulating Files SoftUni Team Technical Trainers Software University
Windows Programming Using C# Regular Expressions, Files & directories Delegates.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
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.
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
CS360 Windows Programming
Chapter 14: Files and Streams. 2Microsoft Visual C# 2012, Fifth Edition Files and the File and Directory Classes Temporary storage – Usually called computer.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
Chapter 8 Files 1/4/20161Copyright © 2012 Thomas P. Skinner.
Text Files and String Processing
CSC 298 Streams and files.
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,
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.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Files and Streams Lec Introduction  Files are used for long-term retention of large amounts of data, even after the program that created the.
File Output Writing data out to a file 1. Output to files  StreamWriter : An object in the System.IO namespace that lets you print output to a destination.
Chapter 6: Creating Windows–based Applications 1 Microsoft® Visual C# 2008.
Lecture 18 File I/O Richard Gesick. File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input)
Fundamentals of.NET NYU-SCPS. Session 6 Exception Handling Exception Handling Streams Streams Files and Directories Files and Directories Working with.
INF230 Basics in C# Programming
Module 6: Building .NET–based Applications with C#
Input and Output 23: Input and Output
Object Writing in files
C# Programming: From Problem Analysis to Program Design
18 Files and Streams.
Serialization.
Defiana Arnaldy, M.Si File and Stream I/O Defiana Arnaldy, M.Si
File Types, Using Streams, Manipulating Files
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
How to work with files and data streams
Files and Streams.
C# Programming: From Problem Analysis to Program Design
Chapter 3 The .NET Framework Class Library (FCL)
Files and Streams Lect3 CT1411.
File Input/Output (I/O)
טיפול בקבצים ליווי מקצועי : ארז קלר
Files & Streams.
Object Oriented Programming
Files and Streams Lect10 GC201 12/1/2015.
Lecture 16 File I/O Richard Gesick.
Fundaments of Game Design
How to work with files and data streams
Files and Streams.
Presentation transcript:

Input and Output 23: Input and Output Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Objectives Survey IO facilities in .NET Framework Class Library 23: Input and Output Objectives Survey IO facilities in .NET Framework Class Library file and directory management text files binary files object serialization Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

IO Library Input/output library in System.IO namespace 23: Input and Output IO Library Input/output library in System.IO namespace Support provided for: file and directory management text files binary files simple type conversion to/from binary Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

23: Input and Output Files and directories Two primary classes to work with files and directories perform file system interaction generally do not manipulate file contents derived from common base FileSystemInfo DirectoryInfo FileInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

FileSystemInfo Files and directories have some operations in common 23: Input and Output FileSystemInfo Files and directories have some operations in common provided in base class FileSystemInfo public abstract class FileSystemInfo ... { public abstract string Name { get; } public string FullName { get; } public string Extension { get; } public abstract bool Exists { get; } public DateTime CreationTime { get; set; } public DateTime LastAccessTime { get; set; } public DateTime LastWriteTime { get; set; } public FileAttributes Attributes { get; set; } public void Delete() ... ... } name characteristics delete Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

DirectoryInfo DirectoryInfo represents a directory 23: Input and Output DirectoryInfo DirectoryInfo represents a directory methods provided to examine and manipulate inherits common operations from FileSystemInfo public sealed class DirectoryInfo : FileSystemInfo { public DirectoryInfo(string path) ... public DirectoryInfo Parent { get; } public DirectoryInfo Root { get; } public void Create () ... public void MoveTo (string destDirName) ... public void Delete (bool recursive ) ... public DirectoryInfo CreateSubdirectory(string path ) ... public FileInfo [] GetFiles () ... public DirectoryInfo [] GetDirectories () ... public FileSystemInfo[] GetFileSystemInfos() ... ... } constructor navigation manipulation contents Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

FileInfo FileInfo represents a file 23: Input and Output FileInfo FileInfo represents a file methods provided to examine and manipulate inherits common operations from FileSystemInfo public sealed class FileInfo : FileSystemInfo { public FileInfo(string fileName) ... public long Length { get; } public string DirectoryName { get; } public DirectoryInfo Directory { get; } public FileInfo CopyTo(string destFileName) ... public FileInfo CopyTo(string destFileName, bool overwrite) ... public void MoveTo(string destFileName) ... ... } constructor length location manipulation Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Application: List contents 23: Input and Output Application: List contents Can examine contents of a directory void List(string path) { DirectoryInfo directory = new DirectoryInfo(path); FileInfo [] files = directory.GetFiles (); DirectoryInfo[] directories = directory.GetDirectories(); foreach (FileInfo f in files) Console.WriteLine(f.Name); foreach (DirectoryInfo d in directories) Console.WriteLine(d.Name); } contents files directories Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Application: Find file 23: Input and Output Application: Find file Can search file system to find specified files void Find(string filename, DirectoryInfo root, ArrayList results) { foreach (FileInfo f in root.GetFiles(filename)) results.Add(f.FullName); foreach (DirectoryInfo d in root.GetDirectories()) Find(filename, d, results); } search with pattern recursive call for each subdirectory DirectoryInfo root = new DirectoryInfo(@"C:\WINDOWS"); ArrayList results = new ArrayList(); Find("mscoree.dll", root, results); foreach (string s in results) Console.WriteLine(s); Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

23: Input and Output Utility classes Three utility classes also work with files and directories Path Directory File Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Path Path provides static methods to manipulate a path string 23: Input and Output Path Path provides static methods to manipulate a path string most do not interact with the file system public sealed class Path { public static bool HasExtension (string path) ... public static string GetExtension (string path) ... public static string ChangeExtension(string path, string extension) ... public static string GetDirectoryName(string path) ... public static string GetFileName (string path) ... public static string GetFileNameWithoutExtension(string path) ... public static readonly char DirectorySeparatorChar; public static readonly char VolumeSeparatorChar; public static readonly char PathSeparator; ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Application: parse path 23: Input and Output Application: parse path Path methods useful to parse path into constituent parts public void Parse(string path) { string a = Path.GetDirectoryName (path); string b = Path.GetFileName (path); string c = Path.GetFileNameWithoutExtension(path); string d = Path.GetExtension (path); string e = Path.GetPathRoot (path); ... } C:\WINDOWS\system32 mscoree.dll mscoree .dll C:\ string path = @"C:\WINDOWS\system32\mscoree.dll"; Parse(path); Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Directory Directory has static methods to manipulate directories 23: Input and Output Directory Directory has static methods to manipulate directories most have analogues in DirectoryInfo several offer unique functionality public sealed class Directory { public static string[] GetLogicalDrives() public static string GetCurrentDirectory() public static void SetCurrentDirectory(string path) public static bool Exists (string path) ... public static string[] GetFiles (string path) ... public static string[] GetDirectories(string path) ... public static void Delete (string path) public static void Move(string source, string dest) ... } all drives on system current directory similar methods in DirectoryInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Application: examine drives 23: Input and Output Application: examine drives Can examine all logical drives use Directory.GetLogicalDrives to get drives use Directory.Exists to determine if disk in drive all drives string[] drives = Directory.GetLogicalDrives(); foreach (string s in drives) { if (Directory.Exists(s)) ... } disk in drive? Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

File File has static methods to manipulate files 23: Input and Output File File has static methods to manipulate files all have analogues in FileInfo public sealed class File { public static bool Exists(string path) ... public static void Delete(string path) ... public static void Copy (string source, string dest) ... public static void Move (string source, string dest) ... ... } similar methods in FileInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Choice of file / directory class 23: Input and Output Choice of file / directory class Must sometimes decide which class to use File vs. FileInfo Directory vs. DirectoryInfo Static methods can offer more convenient usage syntax require permission check on each call Instance methods must instantiate object some permission checks can be done once in constructor Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

File contents manipulation 23: Input and Output File contents manipulation Classes provided to manipulate file contents separate classes for text and binary files filters convert simple types to/from bytes for binary storage support for disk or memory files Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Character IO Classes provided to do character IO 23: Input and Output Character IO Classes provided to do character IO most methods defined in base classes derived classes specialized for data location and operation TextReader TextWriter StreamWriter StringWriter StreamReader StringReader write to disk write to StringBuilder read from disk read from string Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

StreamWriter StreamWriter writes characters to text file 23: Input and Output StreamWriter StreamWriter writes characters to text file open file with one of many constructors write with overloaded Write / WriteLine methods close automatically converted to string using ToString char, bool, string, short, int, long, float, double, etc. text file open StreamWriter sw = new StreamWriter("Chores.txt"); int n = 3; sw.WriteLine("Go to pet store"); sw.Write("Feed all "); sw.Write(n); sw.WriteLine(" cats"); sw.Close(); write close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

StreamReader StreamReader reads characters from text file 23: Input and Output StreamReader StreamReader reads characters from text file open file with one of many constructors read characters or strings with Read / ReadLine methods close can read only char or string char, string text file open StreamReader sr = new StreamReader("Chores.txt"); string s; while ((s = sr.ReadLine()) != null) Console.WriteLine(s); sr.Close(); read close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Byte IO Classes provided to do byte IO 23: Input and Output Byte IO Classes provided to do byte IO most methods defined in base class Two possible data locations provided in System.IO disk memory Stream FileStream MemoryStream read/write disk read/write byte array Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Stream methods Stream offers extensive functionality 23: Input and Output Stream methods Stream offers extensive functionality read / write bytes random access asynchronous read / write public abstract class Stream ... { public virtual int ReadByte () ... public virtual void WriteByte(byte value) ... public abstract int Read (byte[] buffer, int offset, int count); public abstract void Write(byte[] buffer, int offset, int count); public abstract long Seek (long offset, SeekOrigin origin); public abstract long Position { get; set; } public virtual IAsyncResult BeginRead (...) ... public virtual int EndRead (...) ... public virtual IAsyncResult BeginWrite(...) ... public virtual void EndWrite (...) ... ... } read/write random access asynch Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

FileStream FileStream supports read / write bytes to disk file open 23: Input and Output FileStream FileStream supports read / write bytes to disk file open FileStream f = new FileStream ( "Bytes.dat", FileMode.Create, FileAccess.ReadWrite ); f.WriteByte((byte)10); f.WriteByte((byte)20); f.WriteByte((byte)30); f.WriteByte((byte)90); f.WriteByte((byte)50); f.Seek(-2, SeekOrigin.Current); f.WriteByte((byte)40); f.Seek(0, SeekOrigin.Begin); int b = f.ReadByte(); f.Close(); byte, byte[] binary file write back up 2 bytes back up to beginning close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Simple type output BinaryWriter converts many core types to binary 23: Input and Output Simple type output BinaryWriter converts many core types to binary must be used with a stream for storage Write methods convert and write bytes to backing stream char, bool, string, short, int, long, float, double, etc. simple types converter bytes binary file data store FileStream data = new FileStream("Bytes.dat", FileMode.Create); BinaryWriter converter = new BinaryWriter(data); converter.Write(17); converter.Write(3.14); converter.Write("hello"); converter.Close(); converter write close both streams Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Simple type input BinaryReader reconstructs types from binary 23: Input and Output Simple type input BinaryReader reconstructs types from binary must be given a stream containing bytes Read methods read from backing stream and convert char, bool, string, short, int, long, float, double, etc. simple types converter bytes binary file data store FileStream data = new FileStream("Bytes.dat", FileMode.Open); BinaryReader converter = new BinaryReader(data); int i = converter.ReadInt32 (); double d = converter.ReadDouble(); string s = converter.ReadString(); converter.Close(); converter read close both streams Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Serialization Can save/restore state of object to stream 23: Input and Output Serialization Can save/restore state of object to stream called serialization save x 1 y 2 serialize Point x=1, y=2 ... restore deserialize x 1 y 2 Point x=1, y=2 ... Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Serializable attribute 23: Input and Output Serializable attribute Type author must explicitly allow serialization tag with Serializable attribute to allow otherwise get SerializationException allow points to be serialized [Serializable] class Point { int x; int y; ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Formatter BinaryFormatter used to serialize/deserialize object 23: Input and Output Formatter BinaryFormatter used to serialize/deserialize object in namespace System.Runtime.Serialization.Formatters.Binary public sealed class BinaryFormatter ... { public void Serialize(Stream destination, object o) ... } public object Deserialize(Stream source) save object to stream restore object from stream Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Save Use Serialize method to save object to stream void Write() { 23: Input and Output Save Use Serialize method to save object to stream void Write() { FileStream dest = new FileStream("MyData.dat", FileMode.Create); Point data = new Point(1, 2); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(dest, data); ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Restore Use Deserialize method to restore object from stream 23: Input and Output Restore Use Deserialize method to restore object from stream return type is object, typical to downcast void Read() { FileStream source = new FileStream("MyData.dat", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Point data = (Point)formatter.Deserialize(source); ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Object graph Serialization preserves object graph 23: Input and Output Object graph Serialization preserves object graph all referenced objects are serialized graph rebuilt when deserialized x 1 y 2 center radius 3 c Both circle and center point would be serialized Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Summary IO facilities provided by .NET Framework class library 23: Input and Output Summary IO facilities provided by .NET Framework class library in System.IO namespace Can manipulate files and directories Can read/write file contents characters bytes Can convert simple types to/from binary format Serialization allows objects to be read/written to stream Programming C# © 2003 DevelopMentor, Inc. 12/1/2003