streams & file input/output basics c#.net development version 1.1
TRANSCRIPT
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 2
byte stream of bytes byte
Stream
source(writer)
sink(reader)
4 3 2 1 0
What do stream methods do?Open() //opens a streamClose() //closes and flushes a streamFlush() //flushes buffered data in a streamWrite() //writes to a stream (writer is better)Read() //reads from a stream (reader is better)throw IOException
Copyright © 2003-2011 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 © 2003-2011 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 © 2003-2011 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 © 2003-2011 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 © 2003-2011 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 © 2003-2011 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 9
Text File Basicsusing System;using System.IO;using System.Windows.Forms; //Must add reference for MessageBox and SaveFileDialog
namespace TextFiles_101{ static class TextFileProgram { const int MAX = 5; [STAThread] static void Main() { FileStream _fs = null; StreamWriter _sw = null; StreamReader _sr = null; SaveFileDialog _SaveDlg = null; string _FileName = null; string _TempStg = null; try { _SaveDlg = new SaveFileDialog(); _SaveDlg.Filter = "Text File (*.txt)|*.txt|All Files (*.*)|*.*"; _SaveDlg.FilterIndex = 1; _SaveDlg.ShowDialog(); _FileName = _SaveDlg.FileName; _fs = new FileStream(_FileName, FileMode.Create, FileAccess.Write); _sw = new StreamWriter(_fs); for (int i = 1; i <=MAX; i++) _sw.WriteLine(i); _sw.Close(); _sw = null; _fs = new FileStream(_FileName, FileMode.Open, FileAccess.Read); _sr = new StreamReader(_fs); _TempStg = _sr.ReadToEnd(); _fs.Seek(0, SeekOrigin.Begin); for (int i = 0; i <=MAX; i++) { _TempStg = _sr.ReadLine(); if (_TempStg == null) break; Console.WriteLine(_TempStg); } _sr.Close(); _sr = null; } catch (IOException ioexp) { MessageBox.Show("IOException " + ioexp.Message, "IOException", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); } catch (Exception exp) { MessageBox.Show("Unknown Exception " + exp.Message, "Unknown Exception", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); } finally { if (_sw != null) _sw.Close(); if (_sr != null) _sr.Close(); if (_fs != null) _fs.Close(); } Console.ReadLine(); } }//end class TextFileProgram}//end namespace TextFiles_101
FileMode Enumeration CreateNew
Specifies that the operating system should create a new file. This requires FileIOPermissionAccess..::.Write. If the file already exists, an IOException is thrown.
Create Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This
requires FileIOPermissionAccess..::.Write. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.
Open Specifies that the operating system should open an existing file. The ability to open the file is dependent on the value
specified by FileAccess. A System.IO..::.FileNotFoundException is thrown if the file does not exist.
OpenOrCreate Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is
opened with FileAccess.Read, FileIOPermissionAccess..::.Read is required. If the file access is FileAccess.Write then FileIOPermissionAccess..::.Write is required. If the file is opened with FileAccess.ReadWrite, both FileIOPermissionAccess..::.Read and FileIOPermissionAccess..::.Write are required. If the file access is FileAccess.Append, then FileIOPermissionAccess..::.Append is required.
Truncate Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its
size is zero bytes. This requires FileIOPermissionAccess..::.Write. Attempts to read from a file opened with Truncate cause an exception.
Append Specifies that a file is opened and the file if it exists and seeks to the end of the file, or creates a new file.
FileMode.Append can only be used in conjunction with FileAccess.Write. Attempting to seek to a position before the end of the file will throw an IOException and any attempt to read fails and throws an NotSupportedException.
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 10
FileAccess Enumeration Read
Read access to the file. Data can be read from the file. Combine with Write for read/write access.
Write Write access to the file. Data can be written to the
file. Combine with Read for read/write access. ReadWrite
Read and write access to the file. Data can be written to and read from the file.
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 11
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 12
Binary File Basicsclass DataClass{ string ss,se; 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("Start"); bw.Write(i); bw.Write(c); bw.Write(b); bw.Write("End"); bw.Flush(); } public void SeekThySelf() { fs.Seek(6,SeekOrigin.Begin); } public void ReadThySelf() { DataClass ret = new DataClass(fs); br = new BinaryReader(fs); //ret.ss = br.ReadString(); ret.i = br.ReadInt32(); ret.c = br.ReadChar(); ret.b = br.ReadBoolean(); ret.se = br.ReadString(); } public void CleanUpThySelf() { if (bw != null) bw.Close(); if (br != null) br.Close(); if (fs != null) fs.Close(); }}//end class DataClass
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 13
Binary File Basics (Main())using System;using System.IO;using System.Windows.Forms;
static class Program{ static public void Main() { DataClass dc1 = null; try { dc1 = new DataClass(new FileStream(@"G:\Moo.bin", FileMode.Create, FileAccess.ReadWrite)); dc1.WriteThySelf(); dc1.SeekThySelf(); dc1.ReadThySelf(); } catch (IOException ioexp) { MessageBox.Show("IOException -> " + ioexp.Message); } catch (Exception exp) { MessageBox.Show("Exception -> " + exp.Message); } finally { MessageBox.Show("finally -> Cleaning Up"); dc1.CleanUpThySelf(); } }}//end class Program
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 14
Directory static class
Manage directory stuff duh!
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 15
Directory
Much like File But deals with directories!
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 16
Directory Members Delete() Exists() GetCreationTime() GetCurrentDirectory() GetDirectories() GetDirectoryRoot() GetFileSystemEntries()
Sub-directories and files
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 17
Directory Members GetLastAccessTime() GetLastWriteTime() GetLogicalDrives()
Returns disk drives on the machine in a string
GetParent() Move() SetCreationTime() SetCurrentDirectory()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 18
Directory Members
SetLastAccessTime() SetLastWriteTime()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 19
DirectoryInfo
Provides the same info Directory will But you can create instances
(Not static!)
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 20
Path static class
To manage path stuff duh!
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 21
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 C#
@“\\<server>\<share>\<relative path>”
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 22
using System; using System.IO; class Test { public static void Main() { string path1 = @"c:\temp\MyTest.txt"; string path2 = @"c:\temp\MyTest"; string path3 = @"temp"; 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 23
Public Path Fields
AltDirectorySeparatorChar DirectorySeparatorChar InvalidPathChars PathSeparator VolumeSeparatorChar
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 24
Path Methods ChangeExtension() Combine() GetDirectoryName() GetExtension() GetFileName() GetFileNameWithoutExtension() GetFullPath() GetPathRoot() GetTempFileName()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 25
Path Methods cont
GetTempPath() HasExtension() IsPathRooted()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 26
File static class
File’s job is to do file handling Can use it much like a command line
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 27
File Methods AppendText () Copy () Create () CreateText () Delete () Exists () GetAttributes() GetCreationTime()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 28
File Methods GetLastAccessTime() GetLastAccessTime() GetLastWriteTime() Move() Open()
Returns a FileStream
OpenRead() OpenText()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 29
File Methods
OpenWrite() SetAttributes() SetCreationTime() SetLastAccessTime() SetLastWriteTime()
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 30
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 31
FileInfo
Length Size in bytes
DirectoryName Extension FullName
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 32
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 33
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 34
System.IO namespace BinaryReaderReads primitive data types as binary values in a specific encoding. BinaryWriterWrites primitive types in binary to a stream and supports writing strings in a specific encoding. BufferedStreamAdds a buffering layer to read and write operations on another stream. This class cannot be inherited. DirectoryExposes static methods for creating, moving, and enumerating through directories and subdirectories. DirectoryInfoExposes instance methods for creating, moving, and enumerating through directories and subdirectories. DirectoryNotFoundExceptionThe exception that is thrown when part of a file or directory cannot be found. EndOfStreamExceptionThe exception that is thrown when reading is attempted past the end of a stream. ErrorEventArgsProvides data for the Error event. FileProvides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. FileInfoProvides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. FileLoadExceptionThe exception that is thrown when a managed assembly is found but cannot be loaded. FileNotFoundExceptionThe exception that is thrown when an attempt to access a file that does not exist on disk fails. FileStreamExposes a Stream around a file, supporting both synchronous and asynchronous read and write operations. FileSystemEventArgsProvides data for the directory events: Changed, Created, Deleted. FileSystemInfoProvides the base class for both FileInfo and DirectoryInfo objects. FileSystemWatcherListens to the file system change notifications and raises events when a directory, or file in a directory,
changes. InternalBufferOverflowExceptionThe exception thrown when the internal buffer overflows. IODescriptionAttributeSets the description visual designers can display when referencing an event, extender, or property. IOExceptionThe exception that is thrown when an I/O error occurs. MemoryStreamCreates a stream whose backing store is memory. PathPerforms operations on String instances that contain file or directory path information. These operations are performed in
a cross-platform manner. PathTooLongExceptionThe exception that is thrown when a pathname or filename is longer than the system-defined maximum
length . RenamedEventArgsProvides data for the Renamed event. StreamProvides a generic view of a sequence of bytes. StreamReaderImplements a TextReader that reads characters from a byte stream in a particular encoding. StreamWriterImplements a TextWriter for writing characters to a stream in a particular encoding. StringReaderImplements a TextReader that reads from a string. StringWriterImplements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.TextReaderRepresents a reader that can read a sequential series of characters. TextWriterRepresents a writer that can write a sequential series of characters. This class is abstract.Structures
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 35
File.OpenFileInfo.Open
FileStream Constructoretc.
O’Reily C# Text
BufferedStreamStream
(abstract base class for all streams)NetworkStream
CryptoStream FileStream MemoryStream
IsolatedStorageFileStream
TextReaderTextWriter
StringReaderStringWriter
StreamReaderStreamWriter
BinaryReaderBinaryWriter
text binary
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 36
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 37
public class FileSerialization{ private FileStream fs; private BinaryFormatter bf; private SortedDictionary<uint, Data> DirData; public FileSerialization() { DirData = new SortedDictionary<uint, Data>
{ {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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 38
public void BinaryFormatWriter(){ try { fs = new FileStream(@"G:\BinaryFormat.bn", FileMode.Create, 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 39
public void BinaryFormatReader(){ try { fs = new FileStream(@"G:\BinaryFormat.bin", FileMode.Open, FileAccess.Read); bf = new BinaryFormatter(); DirData.Clear(); DirData = (SortedDictionary<uint, Data>)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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 40
using System;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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 41
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 42
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 43
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 44
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 45
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 46
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 47
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 48
MemoryStream Constructorsusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 49
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 50
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 51
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 52
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 53
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 54
Newer Way
Allow XML serialization to worry about that stuff for you
Practically hidden from the programmer
System.XML System.XML.Serialization
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 55
XMLSerializerclass 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 56
Result<?xml version="1.0" encoding="utf-8" ?> <StudentInfo
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>Dennis Fairclough</name> <age>2147483647</age> <gpa>2</gpa> <IQ>50</IQ> </StudentInfo>
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 57
Deserialization
Almost the same as serialization Retrieves the entire object Cast is required
Deserialization returns generic object reference
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 58
Deserializationclass 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 59
Collections and XML
Collections are not “strongly typed” object typed
Thus you need to know the underlying types
Use this with XmlArrayItem
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 60
XmlArrayItempublic 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 61
XmlArrayItem<?xml version="1.0" encoding="utf-8" ?>
<StudentInfo xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"> <name>Dennis Fairclough</name> <age>2147483647</age> <gpa>2</gpa> <IQ>50</IQ>
<items> <int>5</int> </items> </StudentInfo>
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 62
XmlArrayItem
Supports inheritance Supports multiple objects
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 63
XmlArrayItempublic 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 64
XmlArrayItem <?xml version="1.0" encoding="utf-8" ?>
<StudentInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>Dennis Fairclough</name> <age>2147483647</age> <gpa>2</gpa> <IQ>50</IQ>
<items> <int>5</int> <string>Dennis</string> </items> </StudentInfo>
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 65
Inheritancepublic 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 66
Inheritanceclass 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 67
Inheritance <?xml version="1.0" encoding="utf-8" ?>
<StudentInfo xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <name>Dennis Faiclough</name> <age>2147483647</age> <gpa>2</gpa> <IQ>50</IQ>
<items> <Bottom>
<i>5</i> </Bottom>
<Top> <i>6</i> </Top> </items> </StudentInfo>
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 68
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 69
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 70
Representing other types<?xml version="1.0" encoding="utf-8" ?>
<MyClassWithFont xmlns:xsd= "http://www.w3.org/2001/XMLSchema"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema- instance"> <FontString>Microsoft Sans
Serif|12</FontString> </MyClassWithFont>
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 71
Representing other typesclass 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 72
JPG
Can do with cooperation of streams and XML
Convert JPG to string Actually, almost anything can be
converted to a string
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 73
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 74
Word to the Wise
‘\u0000’ is an illegal XML Character Don’t allow your types to insert it into
the file RTF
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 75
Common Dialog Boxes
OpenFileDialog properties methods
SaveFileDialog properties methods
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 76
OpenFileDialog OpenFileDialog Constructor Public Properties AddExtension
(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.
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.
Container (inherited from Component)Gets the IContainer that contains the Component. DefaultExt (inherited from FileDialog)Gets or sets the default file name extension. 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). FileName (inherited from FileDialog) 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. Filter (inherited from FileDialog) 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) 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) 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. ReadOnlyCheckedGets or sets a value indicating whether the read-only check box is selected. RestoreDirectory (inherited from FileDialog)Gets or sets a value indicating whether the dialog box restores the current
directory before closing. ShowHelp (inherited from FileDialog)Gets or sets a value indicating whether the Help button is displayed in the file dialog. ShowReadOnlyGets or sets a value indicating whether the dialog box contains a read-only check box. Site (inherited from Component)Gets or sets the ISite of the Component. Title (inherited from FileDialog)Gets or sets the file dialog box title. ValidateNames (inherited from FileDialog)Gets or sets a value indicating whether the dialog box accepts only valid Win32 file
names.
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 77
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. Dispose (inherited from Component)Overloaded. Releases the resources used by the Component. Equals (inherited from Object) Supported by the .NET Compact Framework. Overloaded. Determines whether two Object instances are equal. GetHashCode (inherited from Object) 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. GetType (inherited from Object) Supported by the .NET Compact Framework. Gets the Type of the current instance. InitializeLifetimeService (inherited from MarshalByRefObject)Obtains a lifetime service object to
control the lifetime policy for this instance. OpenFileOpens the file selected by the user, with read-only permission. The file is specified by the
FileName property. ResetOverridden. See FileDialog.Reset.
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 78
BufferedStream
Wrapper Buffers data Less calls to reads and writes Saves time when needed
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 79
Buffer Size
Determined by you via the constructor
4096 bytes is default
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 80
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 81
BufferedStreamusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 82
BufferedStreamusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 83
BufferedStreamusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 84
BufferedStreamusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 85
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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 86
BufferedStreamusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 87
String IO
StreamReader and StreamWriter Strings in memory use string reader
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 88
StringBuilder
C# mutable string Behaves like C++ strings Can append, remove, etc. Mainly a wrapper of a string that
gives dynamic behavior
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 89
StringReader and StringWriter
Used for reading/writing from strings Text
Duh
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 90
StringReader
Reads string objects StringBuilder ToString() converts to a
string Fascinating I’m sure
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 91
StringReaderusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 92
StringWriter
Uses StringBuilder Needs a mutable string
Copyright © 2003-2011 by Dennis A. Fairclough all rights reserved. 93
StringWriterusing 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 © 2003-2011 by Dennis A. Fairclough all rights reserved. 94
A Dumb Slideusing 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(); }}