Streams & File Input/Output Basics C#.Net Development Version 1.0.

Slides:



Advertisements
Similar presentations
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: File and Stream Tujuan Instruksional Khusus: Mahasiswa dapat.
Advertisements

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.
ASP.NET Programming with C# and SQL Server First Edition
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.
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.
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION.
 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.
Introduction to Exception Handling and Defensive Programming.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
1 COMP3100e Developing Microsoft.Net Applications for Windows (Visual Basic.Net) Class 6 COMP3100E.
Object Oriented Software Development 10. Persistent Storage.
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.
CS360 Windows Programming
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Input and Output 23: Input and Output
CSC 298 Streams and files.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
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.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
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#.Net Software Development Version 1.0. Overview Inheritance Member Access Constructors Polymorphism (Name Hiding) Multilevel Hierarchy Virtual and VTable.
Chapter 6: Creating Windows–based Applications 1 Microsoft® Visual C# 2008.
INF230 Basics in C# Programming
Module 6: Building .NET–based Applications with C#
Data Abstraction: The Walls
Streams & File Input/Output Basics
Input and Output 23: Input and Output
University of Central Florida COP 3330 Object Oriented Programming
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
I/O Basics.
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
How to work with files and data streams
CSCI 3327 Visual Basic Chapter 11: Files and Streams
Files and Streams.
Chapter 13: File Input and Output
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Topics Introduction to File Input and Output
טיפול בקבצים ליווי מקצועי : ארז קלר
Files & Streams.
Files and Streams Lect10 GC201 12/1/2015.
Introduction to Data Structure
How to work with files and data streams
Introduction to Programming
Files and Streams.
Topics Introduction to File Input and Output
CMPE212 – Reminders Assignment 2 due next Friday.
Review for Midterm 3.
Presentation transcript:

Streams & File Input/Output Basics C#.Net Development Version 1.0

Copyright © by Dennis A. Fairclough all rights reserved. 2 byte stream of bytes byte Stream source (writer) sink (reader) What do stream methods do? Open() //opens a stream Close() //closes and flushes a stream Flush() //flushes buffered data in a stream Write() //writes to a stream (writer is better) Read() //reads from a stream (reader is better) throw IOException

Copyright © by Dennis A. Fairclough all rights reserved. 3 A word to the wise!  Wrap ALL stream access messages and code in a try-catch-finally! try { //stream access messages } catch(IOException ioexp) { //exception response code } catch(Exception exp) { //exception response code } finally { //stream clean-up, flush and close code }

Copyright © by Dennis A. Fairclough all rights reserved. 4 Streams  System.IO Namespace  Much like other languages Text  Seeking in file Behavior is sometimes undefined Binary  Can seek in file  File IO File Input/Output  Serializing data C# has much easier ways of doing this, but will look into older techniques first

Copyright © by Dennis A. Fairclough all rights reserved. 5 Classes Used for File I/O (Visual Studio Help File) Directory provides static methods for creating, moving, and enumerating through directories and subdirectories. Directory class provides static methods. DirectoryInfo class provides instance methods. DirectoryInfo provides instance methods for creating, moving, and enumerating through directories and subdirectories. DriveInfo provides instance methods for accessing information about a drive. File provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of a FileStream. File class provides static methods. FileInfo class provides instance methods. FileInfo provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of a FileStream. FileInfo contains instance methods. FileStream supports random access to files through its Seek method. FileStream opens files synchronously by default, but supports asynchronous operation as well. FileSystemInfo is the abstract base class for FileInfo and DirectoryInfo. Path provides methods and properties for processing directory strings in a cross-platform manner. DeflateStream provides methods and properties for compressing and decompressing streams using the Deflate algorithm. GZipStream provides methods and properties for compressing and decompressing streams. By default, this class uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats. SerialPort provides methods and properties for controlling a serial port file resource. File, FileInfo, DriveInfo, Path, Directory, and DirectoryInfo are sealed

Copyright © by Dennis A. Fairclough all rights reserved. 6 Common I/O Stream Classes (Visual Studio Help) BufferedStream is a Stream that adds buffering to another Stream such as a NetworkStream. (FileStream already has buffering internally, and a MemoryStream does not need buffering.) A BufferedStream can be composed around some types of streams in order to improve read and write performance. A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. CryptoStream links data streams to cryptographic transformations. Although CryptoStream derives from Stream, it is not part of the System.IO namespace, but is in the System.Security.Cryptography namespace. MemoryStream is a nonbuffered stream whose encapsulated data is directly accessible in memory. This stream has no backing store and might be useful as a temporary buffer. NetworkStream represents a Stream over a network connection. Although NetworkStream derives from Stream, it is not part of the System.IO namespace, but is in the System.Net.Sockets namespace.

Copyright © by Dennis A. Fairclough all rights reserved. 7 Classes Used for Reading from and Writing to Streams (Visual Studio Help File) BinaryReader and BinaryWriter read and write encoded strings and primitive data types from and to Streams. StreamReader reads characters from Streams, using Encoding to convert characters to and from bytes. StreamReader has a constructor that attempts to ascertain what the correct Encoding for a given Stream is, based on the presence of an Encoding-specific preamble, such as a byte order mark. StreamWriter writes characters to Streams, using Encoding to convert characters to bytes. StringReader reads characters from Strings. StringReader allows you to treat Strings with the same API, so your output can be either a Stream in any encoding or a String. StringWriter writes characters to Strings. StringWriter allows you to treat Strings with the same API, so your output can be either a Stream in any encoding or a String. TextReader is the abstract base class for StreamReader and StringReader. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextReader are designed for Unicode character output. TextWriter is the abstract base class for StreamWriter and StringWriter. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextWriter are designed for Unicode character input.

Copyright © by Dennis A. Fairclough all rights reserved. 8 Text Files  Data converted to char’s and written as bytes.  Data read as bytes and converted to char’s and converted to appropriate data type. Two bytes per character (unicode) Remember  Internationalization (Localization)!  Output element is a string containing the text to be written as bytes.  Returned element is bytes converted to a string containing the text read.

Copyright © by Dennis A. Fairclough all rights reserved. 9 Text File Basics using System; using System.IO; using System.Diagnostics; class MainClass { static void Main() { const string FILE_NAME FileStream fs; StreamWriter sw; StreamReader sr; try { fs = new FileStream(FILE_NAME,FileMode.OpenOrCreate,FileAccess.Write); sw = new StreamWriter(fs); for(int i = 0; i < 100; i++) sw.WriteLine(i.ToString()); sw.Close(); fs.Close(); fs = new FileStream(FILE_NAME,FileMode.Open,FileAccess.Read); sr = new StreamReader(fs); for(int i = 0; i < 100; i++) Console.WriteLine(int.Parse(sr.ReadLine())); sr.Close(); fs.Close(); } catch(IOException ioexp) { Console.WriteLine(ioexp.Message+ioexp.StackTrace); } finally { sw.Close(); //What problem can occur? sr.Close(); fs.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 10 Binary File Basics using System; using System.IO; using System.Diagnostics; class DataClass { int i; char c; bool b; FileStream fs; BinaryWriter bw; BinaryReader br; public DataClass(FileStream filestream) { fs = filestream; c = 'a‘; b = true; } public void WriteThySelf() { bw = new BinaryWriter(fs); bw.Write(i); bw.Write(c); bw.Write(b); bw.Flush(); } public void SeekThySelf() { fs.Seek(0,SeekOrigin.Begin); } public static void ReadThySelf() { DataClass ret = new DataClass(); BinaryReader br = new BinaryReader(fs); ret.i = br.ReadInt32(); ret.c = br.ReadChar(); ret.b = br.ReadBoolean(); }

Copyright © by Dennis A. Fairclough all rights reserved. 11 Binary File Basics (Main()) class MainClass { static void Main() { DataClass dc1; dc1 = new DataClass(new dc1.WriteThySelf(); dc1.SeekThySelf(); dc1.ReadThySelf(); }

Copyright © by Dennis A. Fairclough all rights reserved. 12 Directory static class  Manage directory stuff duh!

Copyright © by Dennis A. Fairclough all rights reserved. 13 Directory  Much like File  But deals with directories!

Copyright © by Dennis A. Fairclough all rights reserved. 14 Directory Members  Delete()  Exists()  GetCreationTime()  GetCurrentDirectory()  GetDirectories()  GetDirectoryRoot()  GetFileSystemEntries() Sub-directories and files

Copyright © by Dennis A. Fairclough all rights reserved. 15 Directory Members  GetLastAccessTime()  GetLastWriteTime()  GetLogicalDrives() Returns disk drives on the machine in a string  GetParent()  Move()  SetCreationTime()  SetCurrentDirectory()

Copyright © by Dennis A. Fairclough all rights reserved. 16 Directory Members  SetLastAccessTime()  SetLastWriteTime()

Copyright © by Dennis A. Fairclough all rights reserved. 17 DirectoryInfo  Provides the same info Directory will  But you can create instances (Not static!)

Copyright © by Dennis A. Fairclough all rights reserved. 18 Path static class  To manage path stuff duh!

Copyright © by Dennis A. Fairclough all rights reserved. 19 UNC Names  Paths  can refer to a file or just a directory  can refer to a relative path  can refer to a Universal Naming Convention (UNC) path for a server and share name Example, all the following are acceptable paths:  "c:\\MyDir\\MyFile.txt" in C#  "c:\\MyDir" in C#  "MyDir\\MySubdir" in C#  "\\\\MyServer\\MyShare" in \ \ ”

Copyright © by Dennis A. Fairclough all rights reserved. 20 using System; using System.IO; class Test { public static void Main() { string path1 string path2 string path3 if (Path.HasExtension(path1)) { Console.WriteLine("{0} has an extension.", path1); } if (!Path.HasExtension(path2)) { Console.WriteLine("{0} has no extension.", path2); } if (!Path.IsPathRooted(path3)) { Console.WriteLine("The string {0} contains no root information.", path3); } Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3)); Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath()); Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName()); Console.WriteLine("\r\nThe set of invalid characters in a path is:"); Console.WriteLine("(Note that the wildcard characters '*' and '?' are not invalid.):"); foreach (char c in Path.InvalidPathChars) { Console.WriteLine(c); } Path class Usage

Copyright © by Dennis A. Fairclough all rights reserved. 21 Public Path Fields  AltDirectorySeparatorChar  DirectorySeparatorChar  InvalidPathChars  PathSeparator  VolumeSeparatorChar

Copyright © by Dennis A. Fairclough all rights reserved. 22 Path Methods  ChangeExtension()  Combine()  GetDirectoryName()  GetExtension()  GetFileName()  GetFileNameWithoutExtension()  GetFullPath()  GetPathRoot()  GetTempFileName()

Copyright © by Dennis A. Fairclough all rights reserved. 23 Path Methods cont  GetTempPath()  HasExtension()  IsPathRooted()

Copyright © by Dennis A. Fairclough all rights reserved. 24 File static class  Job is to do file handling  Can use it much like a command line

Copyright © by Dennis A. Fairclough all rights reserved. 25 File Methods  AppendText ()  Copy ()  Create ()  CreateText ()  Delete ()  Exists ()  GetAttributes()  GetCreationTime()

Copyright © by Dennis A. Fairclough all rights reserved. 26 File Methods  GetLastAccessTime()  GetLastWriteTime()  Move()  Open() Returns a FileStream  OpenRead()  OpenText()

Copyright © by Dennis A. Fairclough all rights reserved. 27 File Methods  OpenWrite()  SetAttributes()  SetCreationTime()  SetLastAccessTime()  SetLastWriteTime()

Copyright © by Dennis A. Fairclough all rights reserved. 28 FileInfo  Gives much the same info as File  Unlike File, you create a an instance of FileInfo on a filename  Gives more information than File

Copyright © by Dennis A. Fairclough all rights reserved. 29 FileInfo  Length Size in bytes  DirectoryName  Extension  FullName

Copyright © by Dennis A. Fairclough all rights reserved. 30 System.IO  Datatypes and classes for reading from and writing to data streams and files, and other input/output (I/O) functionality.  Throws IOException when required.

Copyright © by Dennis A. Fairclough all rights reserved. 31 Sytem.IO  Path static class  Directory(static)/DirectoryInfo classes  File(static)/FileInfo classes  DriveInfo class  Registry class  IsolatedStorageFileSystem class  Stream class Associated Stream classes  FileSystemWatcher class

Copyright © by Dennis A. Fairclough all rights reserved. 32 System.IO namespace  BinaryReaderReads primitive data types as binary values in a specific encoding. BinaryReader  BinaryWriterWrites primitive types in binary to a stream and supports writing strings in a specific encoding. BinaryWriter  BufferedStreamAdds a buffering layer to read and write operations on another stream. This class cannot be inherited. BufferedStream  DirectoryExposes static methods for creating, moving, and enumerating through directories and subdirectories. Directory  DirectoryInfoExposes instance methods for creating, moving, and enumerating through directories and subdirectories. DirectoryInfo  DirectoryNotFoundExceptionThe exception that is thrown when part of a file or directory cannot be found. DirectoryNotFoundException  EndOfStreamExceptionThe exception that is thrown when reading is attempted past the end of a stream. EndOfStreamException  ErrorEventArgsProvides data for the Error event. ErrorEventArgsError  FileProvides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of File  FileStream objects. FileStream  FileInfoProvides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileInfo  FileStream objects. FileStream  FileLoadExceptionThe exception that is thrown when a managed assembly is found but cannot be loaded. FileLoadException  FileNotFoundExceptionThe exception that is thrown when an attempt to access a file that does not exist on disk fails. FileNotFoundException  FileStreamExposes a FileStream  Stream around a file, supporting both synchronous and asynchronous read and write operations. Stream  FileSystemEventArgsProvides data for the directory events: Changed, Created, Deleted. FileSystemEventArgsChangedCreatedDeleted  FileSystemInfoProvides the base class for both FileInfo and DirectoryInfo objects. FileSystemInfoFileInfoDirectoryInfo  FileSystemWatcherListens to the file system change notifications and raises events when a directory, or file in a directory, changes. FileSystemWatcher  InternalBufferOverflowExceptionThe exception thrown when the internal buffer overflows. InternalBufferOverflowException  IODescriptionAttributeSets the description visual designers can display when referencing an event, extender, or property. IODescriptionAttribute  IOExceptionThe exception that is thrown when an I/O error occurs. IOException  MemoryStreamCreates a stream whose backing store is memory. MemoryStream  PathPerforms operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner. PathString  PathTooLongExceptionThe exception that is thrown when a pathname or filename is longer than the system-defined maximum length. PathTooLongException  RenamedEventArgsProvides data for the Renamed event. RenamedEventArgsRenamed  StreamProvides a generic view of a sequence of bytes. Stream  StreamReaderImplements a TextReader that reads characters from a byte stream in a particular encoding. StreamReaderTextReader  StreamWriterImplements a StreamWriter  TextWriter for writing characters to a stream in a particular encoding. TextWriter  StringReaderImplements a StringReader  TextReader that reads from a string. TextReader  StringWriterImplements a StringWriter  TextWriter for writing information to a string. The information is stored in an underlying TextWriter  StringBuilder.TextReaderRepresents a reader that can read a sequential series of characters. StringBuilderTextReader  TextWriterRepresents a writer that can write a sequential series of characters. This class is abstract.Structures TextWriter

Copyright © by Dennis A. Fairclough all rights reserved. 33 File.Open FileInfo.Open FileStream Constructor etc. O’Reily C# Text BufferedStream Stream (abstract base class for all streams) NetworkStream CryptoStreamFileStreamMemoryStream IsolatedStorageFileStream TextReader TextWriter StringReader StringWriter StreamReader StreamWriter BinaryReader BinaryWriter text binary

Copyright © by Dennis A. Fairclough all rights reserved. 34 Object Serialization  Ability to write and read object(s) to and from a stream.  Filestream  BinaryFormatter Serialization Deserialization  Serialized objects must be have the [Serializable] attribute

Serialization/Deserialization Copyright © by Dennis A. Fairclough all rights reserved. 35 public class FileSerialization { private FileStream fs; private BinaryFormatter bf; private SortedDictionary DirData; public FileSerialization() { DirData = new SortedDictionary { {100, new Data("Data 1")}, {101, new Data("Data 2")}, {102, new Data("Data 3")}, {103, new Data("Data 4")}, {104, new Data("Data 5")} } … }

Copyright © by Dennis A. Fairclough all rights reserved. 36 public void BinaryFormatWriter() { try { fs = new FileMode.OpenOrCreate, FileAccess.Write); bf = new BinaryFormatter(); bf.Serialize(fs, DirData); } catch (IOException ioexp) { Console.WriteLine("IOException - {0}", ioexp.Message); } catch (Exception exp) { Console.WriteLine("Exception - {0}",exp.Message); } finally { fs.Close(); Console.WriteLine("BinaryFormatWriter finally"); } [Serializable] public class Data { private string _name; public Data(string name) { _name = name; }

Copyright © by Dennis A. Fairclough all rights reserved. 37 public void BinaryFormatReader() { try { fs = new FileMode.Open, FileAccess.Read); bf = new BinaryFormatter(); DirData.Clear(); DirData = (SortedDictionary )bf.Deserialize(fs); } catch (IOException ioexp) { Console.WriteLine("IOException - {0}", ioexp.Message); } catch (Exception exp) { Console.WriteLine("Exception - {0}", exp.Message); } finally { fs.Close(); Console.WriteLine("BinaryFormatReader finally"); }

Copyright © by Dennis A. Fairclough all rights reserved. 38 using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace FileSerialization_01cs { class Program { static void Main() { FileSerialization fileSerialize = new FileSerialization(); fileSerialize.BinaryFormatWriter(); fileSerialize.BinaryFormatReader(); Console.ReadLine(); }

Copyright © by Dennis A. Fairclough all rights reserved. 39 MemoryStream  Like all other streams  Data stored in memory Flushing doesn’t really occur Though still possible  Convenient for having in memory stream behavior  Garbage Collected later

Copyright © by Dennis A. Fairclough all rights reserved. 40 MemoryStream Constructors  Several different ones for different behavior  Can supply the buffer to the stream  MemoryStream(byte[], startIndex, length, writeAble, publiclyVisable)  startIndex + length must be less than the byte array’s length

Copyright © by Dennis A. Fairclough all rights reserved. 41 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { byte[] b = new byte[5]; MemoryStream ms = new MemoryStream(b, 1, 4,true,true); BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); Console.WriteLine(ms.GetBuffer()[1]); // 5 } public MemoryStream ( byte[] buffer, int index, int count, bool writable, bool publiclyVisible )

Copyright © by Dennis A. Fairclough all rights reserved. 42 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { byte[] b = new byte[5]; MemoryStream ms = new MemoryStream(b, 1, 4,true,true); ms.GetBuffer(); // Legal because publiclyVisable BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); Console.WriteLine(ms.GetBuffer()[1]); // 5 }

Copyright © by Dennis A. Fairclough all rights reserved. 43 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { byte[] b = new byte[5]; MemoryStream ms = new MemoryStream(b, 1, 4, true); BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); // publiclyVisible is false Console.WriteLine(b[1]); // 5 }

Copyright © by Dennis A. Fairclough all rights reserved. 44 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { byte[] b = new byte[5]; MemoryStream ms = new MemoryStream(b, 1, 4); // writeable is true // publiclyVisible is false BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); Console.WriteLine(b[1]); // 5 }

Copyright © by Dennis A. Fairclough all rights reserved. 45 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { byte[] b = new byte[5]; // lengths and indexes are defaulted MemoryStream ms = new MemoryStream(b, true); BinaryWriter bw = new BinaryWriter(ms); //PubliclyVisible is false bw.Write(5); Console.WriteLine(b[0]); // 5 }

Copyright © by Dennis A. Fairclough all rights reserved. 46 MemoryStream Constructors using System; using System.IO; class MainClass { static void Main() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); Console.WriteLine(ms.GetBuffer()[0]); // 5 }

Copyright © by Dennis A. Fairclough all rights reserved. 47 XML  HTML like, but well formed  Begin tags and end tags required  Only a single root  Makes a perfect (well formed) tree Enforced, unlike HTML  Tag names are arbitrary No tags have any meaning to XML itself

Copyright © by Dennis A. Fairclough all rights reserved. 48 XML Serialization  Save the state of your objects  A single object in a single file  Single hierarchy  Wrap data in a single object  Save it away  Retrieve it  Uses attributes and metadata about the class

Copyright © by Dennis A. Fairclough all rights reserved. 49 XML Serialization  Visible fields are saved away  Fields must have getters and setters  Or they can be public Will take this approach here to save space Read as a text file  Good or bad?

Copyright © by Dennis A. Fairclough all rights reserved. 50 A Student Info Class // Must be public! public class StudentInfo { public string name = "Dennis Fairclough"; public int age = int.MaxValue; public float gpa = 2.0f; public int IQ = 50; public override bool Equals(object obj) { StudentInfo si = obj as StudentInfo; return this.name == si.name && this.age == si.age && this.IQ == si.IQ; } public override int GetHashCode() {return 0;} }

Copyright © by Dennis A. Fairclough all rights reserved. 51 One Way (Old Way)  Have two separate methods Read() Write()  The methods encrypt in text or binary output Binary much more compact over text Binary much more compact over XML

Copyright © by Dennis A. Fairclough all rights reserved. 52 Newer Way  Allow XML serialization to worry about that stuff for you  Practically hidden from the programmer  System.XML  System.XML.Serialization

Copyright © by Dennis A. Fairclough all rights reserved. 53 XMLSerializer class MainClass { static void Main() { StudentInfo si = new StudentInfo(); // Text based StreamWriter sw = new StreamWriter("c:\\Temp.xml"); XmlSerializer xs = new XmlSerializer(typeof(StudentInfo)); xs.Serialize(sw, si); sw.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 54 Result Dennis Fairclough

Copyright © by Dennis A. Fairclough all rights reserved. 55 Deserialization  Almost the same as serialization  Retrieves the entire object  Cast is required Deserialization returns generic object reference

Copyright © by Dennis A. Fairclough all rights reserved. 56 Deserialization class MainClass { static void Main() { StudentInfo si; StreamReader sr = new StreamReader("c:\\Temp.xml"); XmlSerializer xs = new XmlSerializer(typeof(StudentInfo)); si = (StudentInfo)xs.Deserialize(sr); sr.Close(); Console.WriteLine(si.Equals(new StudentInfo())); // True }

Copyright © by Dennis A. Fairclough all rights reserved. 57 Collections and XML  Collections are not “strongly typed” object typed  Thus you need to know the underlying types  Use this with XmlArrayItem

Copyright © by Dennis A. Fairclough all rights reserved. 58 XmlArrayItem public class StudentInfo { public string name = "Dennis Fairclough"; public int age = int.MaxValue; public float gpa = 2.0f; public int IQ = 50; public override bool Equals(object obj) { StudentInfo si = obj as StudentInfo; return this.name == si.name && this.age == si.age && this.IQ == si.IQ; } public override int GetHashCode() { return 0; } [XmlArrayItem(typeof(int))] public ArrayList items = new ArrayList(); }

Copyright © by Dennis A. Fairclough all rights reserved. 59 XmlArrayItem <StudentInfo xmlns:xsd= xmlns:xsi=" instance"> Dennis Fairclough

Copyright © by Dennis A. Fairclough all rights reserved. 60 XmlArrayItem  Supports inheritance  Supports multiple objects

Copyright © by Dennis A. Fairclough all rights reserved. 61 XmlArrayItem public class StudentInfo { public string name = "Dennis Fairclough"; public int age = int.MaxValue; public float gpa = 2.0f; public int IQ = 50; public override bool Equals(object obj) { StudentInfo si = obj as StudentInfo; return this.name == si.name && this.age == si.age && this.IQ == si.IQ; } public override int GetHashCode() { return 0; } [XmlArrayItem(typeof(int))] [XmlArrayItem(typeof(string))] public ArrayList items = new ArrayList(); }

Copyright © by Dennis A. Fairclough all rights reserved. 62 XmlArrayItem Dennis Fairclough Dennis

Copyright © by Dennis A. Fairclough all rights reserved. 63 Inheritance public class Top { public int i; } public class Bottom : Top { public int i; // Hides } public class StudentInfo { public string name = "Dennis Fairclough"; public int age = int.MaxValue; public float gpa = 2.0f; public int IQ = 50; public override bool Equals(object obj) { StudentInfo si = obj as StudentInfo; return this.name == si.name && this.age == si.age && this.IQ == si.IQ; } public override int GetHashCode() { return 0; } [XmlArrayItem(typeof(Top))] [XmlArrayItem(typeof(Bottom))] public ArrayList items = new ArrayList(); }

Copyright © by Dennis A. Fairclough all rights reserved. 64 Inheritance class MainClass { static void Main() { StudentInfo si = new StudentInfo(); Bottom b = new Bottom(); b.i = 5; si.items.Add(b); Top t = new Top(); t.i = 6; si.items.Add(t); // Text based StreamWriter sw = new StreamWriter("c:\\Temp.xml"); XmlSerializer xs = new XmlSerializer(typeof(StudentInfo)); xs.Serialize(sw, si); sw.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 65 Inheritance <StudentInfo xmlns:xsd= xmlns:xsi=" Dennis Faiclough

Copyright © by Dennis A. Fairclough all rights reserved. 66 Representing other types  XML serialization only supports “primitive” types  So how do we serialize other types? Font Color JPG  Have to convert all fields to “understood” types string int char

Copyright © by Dennis A. Fairclough all rights reserved. 67 Representing other types public class MyClassWithFont { private Font font = new Font("courier", 12f); public string FontString { get { return font.Name + '|' + font.Size; } set { font = new Font(value.Split('|')[0], float.Parse(value.Split('|')[1])); } class MainClass { static void Main() { MyClassWithFont fontClass = new MyClassWithFont(); StreamWriter sw = new StreamWriter("c:\\Temp.xml"); XmlSerializer xs = new XmlSerializer(typeof(MyClassWithFont)); xs.Serialize(sw, fontClass); sw.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 68 Representing other types <MyClassWithFont xmlns:xsd= " xmlns:xsi= " instance"> Microsoft Sans Serif|12

Copyright © by Dennis A. Fairclough all rights reserved. 69 Representing other types class MainClass { static void Main() { MyClassWithFont fontClass; StreamReader sr = new StreamReader("c:\\Temp.xml"); XmlSerializer xs = new XmlSerializer(typeof(MyClassWithFont)); fontClass = xs.Deserialize(sr) as MyClassWithFont; sr.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 70 JPG  Can do with cooperation of streams and XML  Convert JPG to string  Actually, almost anything can be converted to a string

Copyright © by Dennis A. Fairclough all rights reserved. 71 JPG public string ImageToXml { get { MemoryStream ms = new MemoryStream(); Bitmap b = new Bitmap(image); b.Save(ms, ImageFormat.Jpeg); byte[] bytes = ms.GetBuffer(); string ret = Convert.ToBase64String(bytes); b.Dispose(); return ret; } set { byte[] bytes = Convert.FromBase64String(value); MemoryStream ms = new MemoryStream(bytes); image = Image.FromStream(ms); state = State.Printed; }

Copyright © by Dennis A. Fairclough all rights reserved. 72 Word to the Wise  ‘\u0000’ is an illegal XML Character  Don’t allow your types to insert it into the file RTF

Copyright © by Dennis A. Fairclough all rights reserved. 73 Common Dialog Boxes  OpenFileDialog properties methods  SaveFileDialog properties methods

Copyright © by Dennis A. Fairclough all rights reserved. 74 OpenFileDialog  OpenFileDialog ConstructorOpenFileDialog Constructor  Public Properties  AddExtensionAddExtension (inherited from FileDialog)Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.  CheckFileExistsOverridden. Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckFileExists  CheckPathExists (inherited from FileDialog)Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist. CheckPathExists  Container (inherited from Component)Gets the IContainer that contains the Component. ContainerIContainerComponent  DefaultExt (inherited from FileDialog)Gets or sets the default file name extension. DefaultExt  DereferenceLinks (inherited from FileDialog)Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk). DereferenceLinks  FileName (inherited from FileDialog) FileName  Supported by the.NET Compact Framework.  Gets or sets a string containing the file name selected in the file dialog box.  FileNames (inherited from FileDialog)Gets the file names of all selected files in the dialog box. FileNames  Filter (inherited from FileDialog) Filter  Supported by the.NET Compact Framework.  Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.  FilterIndex (inherited from FileDialog) FilterIndex  Supported by the.NET Compact Framework.  Gets or sets the index of the filter currently selected in the file dialog box.  InitialDirectory (inherited from FileDialog) InitialDirectory  Supported by the.NET Compact Framework.  Gets or sets the initial directory displayed by the file dialog box.  MultiselectGets or sets a value indicating whether the dialog box allows multiple files to be selected. Multiselect  ReadOnlyCheckedGets or sets a value indicating whether the read-only check box is selected. ReadOnlyChecked  RestoreDirectory (inherited from FileDialog)Gets or sets a value indicating whether the dialog box restores the current directory before closing. RestoreDirectory  ShowHelp (inherited from FileDialog)Gets or sets a value indicating whether the Help button is displayed in the file dialog. ShowHelp  ShowReadOnlyGets or sets a value indicating whether the dialog box contains a read-only check box. ShowReadOnly  Site (inherited from Component)Gets or sets the ISite of the Component. SiteISiteComponent  Title (inherited from FileDialog)Gets or sets the file dialog box title. Title  ValidateNames (inherited from FileDialog)Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names. ValidateNames

Copyright © by Dennis A. Fairclough all rights reserved. 75 OpenFileDialog Methods  Public Methods  CreateObjRef (inherited from MarshalByRefObject)Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. CreateObjRef  Dispose (inherited from Component)Overloaded. Releases the resources used by the Component. DisposeComponent  Equals (inherited from Object) Equals  Supported by the.NET Compact Framework.  Overloaded. Determines whether two Object instances are equal.Object  GetHashCode (inherited from Object) GetHashCode  Supported by the.NET Compact Framework.  Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.  GetLifetimeService (inherited from MarshalByRefObject)Retrieves the current lifetime service object that controls the lifetime policy for this instance. GetLifetimeService  GetType (inherited from Object) GetType  Supported by the.NET Compact Framework.  Gets the Type of the current instance.Type  InitializeLifetimeService (inherited from MarshalByRefObject)Obtains a lifetime service object to control the lifetime policy for this instance. InitializeLifetimeService  OpenFileOpens the file selected by the user, with read-only permission. The file is specified by the FileName property. OpenFile FileName  ResetOverridden. See FileDialog.Reset. ResetFileDialog.Reset

Copyright © by Dennis A. Fairclough all rights reserved. 76 BufferedStream  Wrapper  Buffers data  Less calls to reads and writes  Saves time when needed

Copyright © by Dennis A. Fairclough all rights reserved. 77 Buffer Size  Determined by you via the constructor  4096 bytes is default

Copyright © by Dennis A. Fairclough all rights reserved. 78 Buffer  Only used if needed If write or read is too large, buffer not used Nor created  Otherwise buffering occurs to save time  Not designed for switching often between reads and writes

Copyright © by Dennis A. Fairclough all rights reserved. 79 BufferedStream using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream()); byte[] b = new byte[4096]; bs.Write(b, 0, b.Length); // Buffer not created or used }

Copyright © by Dennis A. Fairclough all rights reserved. 80 BufferedStream using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream()); byte[] b = new byte[4096]; bs.Write(b, 0, b.Length); // Buffer not created bs.Read(b, 0, b.Length); // Buffer still not used }

Copyright © by Dennis A. Fairclough all rights reserved. 81 BufferedStream using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream()); byte[] b = new byte[4095]; bs.Write(b, 0, b.Length); // Buffer created }

Copyright © by Dennis A. Fairclough all rights reserved. 82 BufferedStream using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream(), 10); byte[] b = new byte[10]; bs.Write(b, 0, b.Length); // Buffer not created or used b = new byte[9]; bs.Write(b, 0, b.Length); }

Copyright © by Dennis A. Fairclough all rights reserved. 83 Can[whatever] using System; using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream(), 10); Console.WriteLine(bs.CanRead); Console.WriteLine(bs.CanWrite); Console.WriteLine(bs.CanSeek); Console.WriteLine(bs.Length); Console.WriteLine(bs.Position); }

Copyright © by Dennis A. Fairclough all rights reserved. 84 BufferedStream using System; using System.IO; class MainClass { static void Main() { BufferedStream bs = new BufferedStream(new MemoryStream(), 10); bs.Close(); Console.WriteLine(bs.CanRead); Console.WriteLine(bs.CanWrite); Console.WriteLine(bs.CanSeek); // Following throws // Console.WriteLine(bs.Length); // Console.WriteLine(bs.Position); }

Copyright © by Dennis A. Fairclough all rights reserved. 85 String IO  StreamReader and StreamWriter  Strings in memory use string reader

Copyright © by Dennis A. Fairclough all rights reserved. 86 StringBuilder  C# mutable string  Behaves like C++ strings  Can append, remove, etc.  Mainly a wrapper of a string that gives dynamic behavior

Copyright © by Dennis A. Fairclough all rights reserved. 87 StringReader and StringWriter  Used for reading/writing from strings  Text Duh

Copyright © by Dennis A. Fairclough all rights reserved. 88 StringReader  Reads string objects  StringBuilder ToString() converts to a string Fascinating I’m sure

Copyright © by Dennis A. Fairclough all rights reserved. 89 StringReader using System; using System.Diagnostics; using System.IO; class MainClass { static void Main() { StringReader sr = new StringReader("xValue = 25"); char[] buf = new char[2]; sr.Read(buf, 1, 1); Debug.Assert(buf[1] == 'x'); }

Copyright © by Dennis A. Fairclough all rights reserved. 90 StringWriter  Uses StringBuilder Needs a mutable string

Copyright © by Dennis A. Fairclough all rights reserved. 91 StringWriter using System; using System.Diagnostics; using System.Text; using System.IO; class MainClass { static void Main() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); sw.Write("This, that"); Debug.Assert(sb.ToString() == "This, that"); }

Copyright © by Dennis A. Fairclough all rights reserved. 92 A Dumb Slide using System; using System.Diagnostics; using System.Text; using System.IO; class MainClass { static void Main() { StreamWriter sw = new StreamWriter("moo"); sw.Write("SomeDumbSlide"); sw.Close(); StreamReader sr = new StreamReader("moo"); string s = sr.ReadToEnd(); Debug.Assert(s == "SomeDumbSlide"); sr.Close(); }

Copyright © by Dennis A. Fairclough all rights reserved. 93 What did you learn?  ??