Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Streams & File Input/Output Basics C#.Net Development Version 1.0."— Presentation transcript:

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

2 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 2 byte stream of bytes byte Stream source (writer) sink (reader) 43210 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 Copyright © 2003-2008 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 }

4 Copyright © 2003-2008 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

5 Copyright © 2003-2008 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

6 Copyright © 2003-2008 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.

7 Copyright © 2003-2008 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.

8 Copyright © 2003-2008 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.

9 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 9 Text File Basics using System; using System.IO; using System.Diagnostics; class MainClass { static void Main() { const string FILE_NAME = @“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 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 10 Binary File Basics using System; using System.IO; using System.Diagnostics; class DataClass { int i; char c; bool b; FileStream fs; BinaryWriter bw; BinaryReader br; public DataClass(FileStream filestream) { fs = filestream; c = 'a‘; b = true; } public void WriteThySelf() { bw = new BinaryWriter(fs); bw.Write(i); bw.Write(c); bw.Write(b); bw.Flush(); } public void SeekThySelf() { fs.Seek(0,SeekOrigin.Begin); } public static void ReadThySelf() { DataClass ret = new DataClass(); BinaryReader br = new BinaryReader(fs); ret.i = br.ReadInt32(); ret.c = br.ReadChar(); ret.b = br.ReadBoolean(); }

11 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 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 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 12 Directory static class  Manage directory stuff duh!

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

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

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

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

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

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

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

20 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 20 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

36 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 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 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 37 public void BinaryFormatReader() { try { fs = new FileStream(@"C:\BinaryFormat.bn", FileMode.Open, FileAccess.Read); bf = new BinaryFormatter(); DirData.Clear(); DirData = (SortedDictionary )bf.Deserialize(fs); } catch (IOException ioexp) { Console.WriteLine("IOException - {0}", ioexp.Message); } catch (Exception exp) { Console.WriteLine("Exception - {0}", exp.Message); } finally { fs.Close(); Console.WriteLine("BinaryFormatReader finally"); }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

54 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 54 Result Dennis Fairclough 2147483647 2 50

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

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

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

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

59 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 59 XmlArrayItem <StudentInfo xmlns:xsd=http://www.w3.org/2001/XMLSchemahttp://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance"> Dennis Fairclough 2147483647 2 50 5

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

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

62 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 62 XmlArrayItem Dennis Fairclough 2147483647 2 50 5 Dennis

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

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

65 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 65 Inheritance <StudentInfo xmlns:xsd=http://www.w3.org/2001/XMLSchemahttp://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> Dennis Faiclough 2147483647 2 50 5 6

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

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

68 Copyright © 2003-2008 by Dennis A. Fairclough all rights reserved. 68 Representing other types <MyClassWithFont xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi= "http://www.w3.org/2001/XMLSchema- instance"> Microsoft Sans Serif|12

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Similar presentations


Ads by Google