Streams & File Input/Output Basics C# .Net Development
Stream byte stream of bytes byte source (writer) sink (reader) 4 3 2 1 0 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
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 }
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
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
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.
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.
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.
Text File Basics using System; using System.IO; using System.Diagnostics; class MainClass { static void Main() { const string FILE_NAME = @“c:Moo.txt"; 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(); } }
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(); } }
Binary File Basics (Main()) class MainClass { static void Main() { DataClass dc1; dc1 = new DataClass(new FileStream(@"c:Moo.bin",FileMode.CreateNew,FileAccess.ReadWrite);); dc1.WriteThySelf(); dc1.SeekThySelf(); dc1.ReadThySelf(); } }
Directory static class • Manage directory stuff • duh!
Directory • Much like File • But deals with directories!
Directory Members • Delete() • Exists() • GetCreationTime() • GetCurrentDirectory() • GetDirectories() • GetDirectoryRoot() • GetFileSystemEntries() • Sub-directories and files
Directory Members • GetLastAccessTime() • GetLastWriteTime() • GetLogicalDrives() • Returns disk drives on the machine in a string • GetParent() • Move() • SetCreationTime() • SetCurrentDirectory()
Directory Members • SetLastAccessTime() • SetLastWriteTime()
DirectoryInfo • Provides the same info Directory will • But you can create instances • (Not static!)
Path static class • To manage path stuff • duh!
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:MyDirMyFile.txt" in C# • "c:MyDir" in C# • "MyDirMySubdir" in C# • "MyServerMyShare" in C# • @“<server><share><relative path>”
Path class Usage using System; using System.IO; class Test { public static void Main() { string path1 = @"c:tempMyTest.txt"; string path2 = @"c:tempMyTest"; 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("rnThe 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); } } }
Public Path Fields • AltDirectorySeparatorChar • DirectorySeparatorChar • InvalidPathChars • PathSeparator • VolumeSeparatorChar
Path Methods • ChangeExtension() • Combine() • GetDirectoryName() • GetExtension() • GetFileName() • GetFileNameWithoutExtension() • GetFullPath() • GetPathRoot() • GetTempFileName()
Path Methods cont • GetTempPath() • HasExtension() • IsPathRooted()
File static class • Job is to do file handling • Can use it much like a command line
File Methods • AppendText () • Copy () • Create () • CreateText () • Delete () • Exists () • GetAttributes() • GetCreationTime()
File Methods • GetLastAccessTime() • GetLastAccessTime() • GetLastWriteTime() • Move() • Open() • Returns a FileStream • OpenRead() • OpenText()
File Methods • OpenWrite() • SetAttributes() • SetCreationTime() • SetLastAccessTime() • SetLastWriteTime()
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
FileInfo • Length • Size in bytes • DirectoryName • Extension • FullName
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.
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
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
File.Open FileInfo.Open FileStream Constructor etc. O’Reily C# Text BufferedStream Stream (abstract base class for all streams) NetworkStream CryptoStream FileStream MemoryStream IsolatedStorageFileStream TextReader TextWriter StringReader StringWriter StreamReader StreamWriter BinaryReader BinaryWriter text binary
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 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")} } } … }
public void BinaryFormatWriter() { try { fs = new FileStream(@"C:BinaryFormat.bn", 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; } }
public void BinaryFormatReader() { try { fs = new FileStream(@"C:BinaryFormat.bn", 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"); } }
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(); } }
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
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
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 )
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 } }
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 } }
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 } }
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 } }
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 } }
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
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
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?
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;} }
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
Newer Way • Allow XML serialization to worry about that stuff for you • Practically hidden from the programmer • System.XML • System.XML.Serialization
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(); } }
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>
Deserialization • Almost the same as serialization • Retrieves the entire object • Cast is required • Deserialization returns generic object reference
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 } }
Collections and XML • Collections are not “strongly typed” • object typed • Thus you need to know the underlying types • Use this with XmlArrayItem
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(); }
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>
XmlArrayItem • Supports inheritance • Supports multiple objects
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(); }
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>
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(); }
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(); } }
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>
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
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(); } }
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>
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(); } }
JPG • Can do with cooperation of streams and XML • Convert JPG to string • Actually, almost anything can be converted to a string
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; } }
Word to the Wise • ‘u0000’ is an illegal XML Character • Don’t allow your types to insert it into the file • RTF
Common Dialog Boxes • OpenFileDialog • properties • methods • SaveFileDialog • properties • methods
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.
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.
BufferedStream • Wrapper • Buffers data • Less calls to reads and writes • Saves time when needed
Buffer Size • Determined by you via the constructor • 4096 bytes is default
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
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 } }
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 } }
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 } }
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); } }
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); } }
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); } }
String IO • StreamReader and StreamWriter • Strings in memory use string reader
StringBuilder • C# mutable string • Behaves like C++ strings • Can append, remove, etc. • Mainly a wrapper of a string that gives dynamic behavior
StringReader and StringWriter • Used for reading/writing from strings • Text • Duh
StringReader • Reads string objects • StringBuilder ToString() converts to a string • Fascinating I’m sure
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'); } }
StringWriter • Uses StringBuilder • Needs a mutable string
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"); } }
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(); } }
What did you learn? • ??

Streams & File Input/Output Basics in c#

  • 1.
    Streams & FileInput/Output Basics C# .Net Development
  • 2.
    Stream byte stream ofbytes byte source (writer) sink (reader) 4 3 2 1 0 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
  • 3.
    A word tothe 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 }
  • 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
  • 5.
    Classes Used forFile 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
  • 6.
    Common I/O StreamClasses (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.
  • 7.
    Classes Used forReading 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.
  • 8.
    Text Files •Data convertedto 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.
  • 9.
    Text File Basics usingSystem; using System.IO; using System.Diagnostics; class MainClass { static void Main() { const string FILE_NAME = @“c:Moo.txt"; 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(); } }
  • 10.
    Binary File Basics usingSystem; 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(); } }
  • 11.
    Binary File Basics(Main()) class MainClass { static void Main() { DataClass dc1; dc1 = new DataClass(new FileStream(@"c:Moo.bin",FileMode.CreateNew,FileAccess.ReadWrite);); dc1.WriteThySelf(); dc1.SeekThySelf(); dc1.ReadThySelf(); } }
  • 12.
    Directory static class •Manage directory stuff • duh!
  • 13.
    Directory • Much likeFile • But deals with directories!
  • 14.
    Directory Members • Delete() •Exists() • GetCreationTime() • GetCurrentDirectory() • GetDirectories() • GetDirectoryRoot() • GetFileSystemEntries() • Sub-directories and files
  • 15.
    Directory Members • GetLastAccessTime() •GetLastWriteTime() • GetLogicalDrives() • Returns disk drives on the machine in a string • GetParent() • Move() • SetCreationTime() • SetCurrentDirectory()
  • 16.
  • 17.
    DirectoryInfo • Provides thesame info Directory will • But you can create instances • (Not static!)
  • 18.
    Path static class •To manage path stuff • duh!
  • 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:MyDirMyFile.txt" in C# • "c:MyDir" in C# • "MyDirMySubdir" in C# • "MyServerMyShare" in C# • @“<server><share><relative path>”
  • 20.
    Path class Usage usingSystem; using System.IO; class Test { public static void Main() { string path1 = @"c:tempMyTest.txt"; string path2 = @"c:tempMyTest"; 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("rnThe 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); } } }
  • 21.
    Public Path Fields •AltDirectorySeparatorChar • DirectorySeparatorChar • InvalidPathChars • PathSeparator • VolumeSeparatorChar
  • 22.
    Path Methods • ChangeExtension() •Combine() • GetDirectoryName() • GetExtension() • GetFileName() • GetFileNameWithoutExtension() • GetFullPath() • GetPathRoot() • GetTempFileName()
  • 23.
    Path Methods cont •GetTempPath() • HasExtension() • IsPathRooted()
  • 24.
    File static class •Job is to do file handling • Can use it much like a command line
  • 25.
    File Methods • AppendText() • Copy () • Create () • CreateText () • Delete () • Exists () • GetAttributes() • GetCreationTime()
  • 26.
    File Methods • GetLastAccessTime() •GetLastAccessTime() • GetLastWriteTime() • Move() • Open() • Returns a FileStream • OpenRead() • OpenText()
  • 27.
    File Methods • OpenWrite() •SetAttributes() • SetCreationTime() • SetLastAccessTime() • SetLastWriteTime()
  • 28.
    FileInfo • Gives muchthe same info as File • Unlike File, you create a an instance of FileInfo on a filename • Gives more information than File
  • 29.
    FileInfo • Length • Sizein bytes • DirectoryName • Extension • FullName
  • 30.
    System.IO • Datatypes andclasses for reading from and writing to data streams and files, and other input/output (I/O) functionality. • Throws IOException when required.
  • 31.
    Sytem.IO •Path static class •Directory(static)/DirectoryInfoclasses •File(static)/FileInfo classes •DriveInfo class •Registry class •IsolatedStorageFileSystem class •Stream class • Associated Stream classes •FileSystemWatcher class
  • 32.
    System.IO namespace • BinaryReaderReadsprimitive 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
  • 33.
    File.Open FileInfo.Open FileStream Constructor etc. O’Reily C#Text BufferedStream Stream (abstract base class for all streams) NetworkStream CryptoStream FileStream MemoryStream IsolatedStorageFileStream TextReader TextWriter StringReader StringWriter StreamReader StreamWriter BinaryReader BinaryWriter text binary
  • 34.
    Object Serialization • Abilityto write and read object(s) to and from a stream. • Filestream • BinaryFormatter • Serialization • Deserialization • Serialized objects must be have the [Serializable] attribute
  • 35.
    Serialization/Deserialization public class FileSerialization { privateFileStream 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")} } } … }
  • 36.
    public void BinaryFormatWriter() { try { fs= new FileStream(@"C:BinaryFormat.bn", 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; } }
  • 37.
    public void BinaryFormatReader() { try { fs= new FileStream(@"C:BinaryFormat.bn", 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"); } }
  • 38.
    using System.Collections.Generic; using System.Text; usingSystem.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(); } }
  • 39.
    MemoryStream • Like allother streams • Data stored in memory • Flushing doesn’t really occur • Though still possible • Convenient for having in memory stream behavior • Garbage Collected later
  • 40.
    MemoryStream Constructors • Severaldifferent 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
  • 41.
    MemoryStream Constructors using System; usingSystem.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 )
  • 42.
    MemoryStream Constructors using System; usingSystem.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 } }
  • 43.
    MemoryStream Constructors using System; usingSystem.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 } }
  • 44.
    MemoryStream Constructors using System; usingSystem.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 } }
  • 45.
    MemoryStream Constructors using System; usingSystem.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 } }
  • 46.
    MemoryStream Constructors using System; usingSystem.IO; class MainClass { static void Main() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(5); Console.WriteLine(ms.GetBuffer()[0]); // 5 } }
  • 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
  • 48.
    XML Serialization • Savethe 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
  • 49.
    XML Serialization • Visiblefields 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?
  • 50.
    A Student InfoClass // 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;} }
  • 51.
    One Way (OldWay) • 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
  • 52.
    Newer Way • AllowXML serialization to worry about that stuff for you • Practically hidden from the programmer • System.XML • System.XML.Serialization
  • 53.
    XMLSerializer class MainClass { static voidMain() { 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(); } }
  • 54.
    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>
  • 55.
    Deserialization • Almost thesame as serialization • Retrieves the entire object • Cast is required • Deserialization returns generic object reference
  • 56.
    Deserialization class MainClass { static voidMain() { 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 } }
  • 57.
    Collections and XML •Collections are not “strongly typed” • object typed • Thus you need to know the underlying types • Use this with XmlArrayItem
  • 58.
    XmlArrayItem public class StudentInfo { publicstring 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(); }
  • 59.
    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>
  • 60.
  • 61.
    XmlArrayItem public class StudentInfo { publicstring 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(); }
  • 62.
    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>
  • 63.
    Inheritance public class Top { publicint 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(); }
  • 64.
    Inheritance class MainClass { static voidMain() { 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(); } }
  • 65.
    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>
  • 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
  • 67.
    Representing other types publicclass 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(); } }
  • 68.
    Representing other types <?xmlversion="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>
  • 69.
    Representing other types classMainClass { 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(); } }
  • 70.
    JPG • Can dowith cooperation of streams and XML • Convert JPG to string • Actually, almost anything can be converted to a string
  • 71.
    JPG public string ImageToXml { get { MemoryStreamms = 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; } }
  • 72.
    Word to theWise • ‘u0000’ is an illegal XML Character • Don’t allow your types to insert it into the file • RTF
  • 73.
    Common Dialog Boxes •OpenFileDialog • properties • methods • SaveFileDialog • properties • methods
  • 74.
    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.
  • 75.
    OpenFileDialog Methods • PublicMethods • 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.
  • 76.
    BufferedStream • Wrapper • Buffersdata • Less calls to reads and writes • Saves time when needed
  • 77.
    Buffer Size • Determinedby you via the constructor • 4096 bytes is default
  • 78.
    Buffer • Only usedif 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
  • 79.
    BufferedStream using System.IO; class MainClass { staticvoid Main() { BufferedStream bs = new BufferedStream(new MemoryStream()); byte[] b = new byte[4096]; bs.Write(b, 0, b.Length); // Buffer not created or used } }
  • 80.
    BufferedStream using System.IO; class MainClass { staticvoid 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 } }
  • 81.
    BufferedStream using System.IO; class MainClass { staticvoid Main() { BufferedStream bs = new BufferedStream(new MemoryStream()); byte[] b = new byte[4095]; bs.Write(b, 0, b.Length); // Buffer created } }
  • 82.
    BufferedStream using System.IO; class MainClass { staticvoid 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); } }
  • 83.
    Can[whatever] using System; using System.IO; classMainClass { 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); } }
  • 84.
    BufferedStream using System; using System.IO; classMainClass { 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); } }
  • 85.
    String IO • StreamReaderand StreamWriter • Strings in memory use string reader
  • 86.
    StringBuilder • C# mutablestring • Behaves like C++ strings • Can append, remove, etc. • Mainly a wrapper of a string that gives dynamic behavior
  • 87.
    StringReader and StringWriter •Used for reading/writing from strings • Text • Duh
  • 88.
    StringReader • Reads stringobjects • StringBuilder ToString() converts to a string • Fascinating I’m sure
  • 89.
    StringReader using System; using System.Diagnostics; usingSystem.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'); } }
  • 90.
  • 91.
    StringWriter using System; using System.Diagnostics; usingSystem.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"); } }
  • 92.
    A Dumb Slide usingSystem; 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(); } }
  • 93.
    What did youlearn? • ??