Title: Network Programming
1Network Programming
- Chapter 2
- Streams in .NET
2Basic Outline
- Streams in .NET
- Stream Manipulation
- Serialisation
3Introduction
- A stream is an abstract representation of a
sequence of bytes (e.g. file, I/O device or
TCP/IP socket) - Abstraction allows us to access different devices
in the same manner (like with inheritance)
4Streams in .NET
- Stream class
- Abstract class
- Perform binary I/O operations
- TextReader TextWriter classes
- BinaryReader BinaryWriter classes
5Streams in .NET
- Synchronous and Asynchronous I/O
- Stream class provides for both synchronous
asynchronous - Stream Class
- FileStream Class
- Reading and Writing with the FileStream Class
- BufferedStream Class
- MemoryStream Class
- NetworkStream Class
- CryptoStream Class
6Synchronous I/O
- Default setting
- Simplest method
- Blocks processing until operation is complete
(disadvantage) - Not suitable for operations over a network
- Not good choice for large files over low
bandwidth - Can simulate asynchronous I/O by threading
7Asynchronous I/O
- Allows other processing
- Operating system notifies caller when I/O
processing is done - Needs separate notification mechanism
- Useful when application needs to process other
tasks while doing I/O - A separate thread is created for each I/O thread
(higher O/S overhead)
8Streams in .NET
- Synchronous and Asynchronous I/O
- Stream Class
- FileStream Class
- Reading and Writing with the FileStream Class
- BufferedStream Class
- MemoryStream Class
- NetworkStream Class
- CryptoStream Class
9Stream Class
System.Security.Cryptography
System.Security.Cryptography.CryptoStream
10Stream Class
- Base class System.IO
- Stream is base class for all other stream classes
11Classes Derived From the Stream Class
12Stream Members
13Synchronous Methods for Reading from and Writing
to a Stream
14Asynchronous Methods for Reading from and Writing
to a Stream
15Methods for Managing a Stream
16Streams in .NET
- Synchronous and Asynchronous I/O
- Stream Class
- FileStream Class
- Reading and Writing with the FileStream Class
- BufferedStream Class
- MemoryStream Class
- NetworkStream Class
- CryptoStream Class
17FileStream Class
- One of the most widely used of the Stream-derived
classes - Handles files and standard input and output
devices - Several ways to create a FileStream object
18Creating a FileStream Instance with a File Path
- Specify a path to a file
- Default buffer is 8192 bytes
- Buffer size may be changed in constructor
- Methods of creating a FileStream
- Specifying the File Path and Mode
- Specifying File Access
- Specifying Sharing Permissions
- Specifying Buffer Size
- Specifying Synchronous or Asynchronous State
19FileMode Options
20FileMode Syntax
- To create a FileStream object that creates a new
file called c\Networking\MyStream.txt, you would
use the following - //Using file path and file mode
- FileStream inF new FileStream(C\\Networking\\M
yStream.txt, FileMode.CreateNew)
21FileAccess Options
22FileAccess Syntax
- You can use the CanRead and CanWrite properties
to check the FileAccess permission given to the
file - To create a new file called c\Networking\MyStream
.txt with write-only access - //Using file path, file mode and file access
- FileStream inF new FileStream(C\\Networking\\M
yStream.txt, FileMode.CreateNew,
FileAccess.Write)
23FileShare Options
24FileShare Syntax
- Create a FileStream instance using the FileMode,
FileAccess and FileShare properties - //Using file path, file mode, file access and
sharing permission - //Open file for writing, other processes will get
read-only access - FileStream inF new FileStream
(C\\Networking\\MyStream.txt, FileMode.Open,
FileAccess.Write, FileShare.Read)
25Specifying Buffer Size
- You can also create a FileStream instance by
specifying the size of the buffer in addition to
the parameters discussed previously. Here we set
the size of the buffer to 1000 bytes - //using path, mode, access, sharing permission
and buffer size - FileStream inF new FileStream(C\\Networking\\M
yStream.txt, FileMode.Open, FileAccess.Write,
FileShare.Read, 1000) - If the buffer size specified is between 0 and 8
bytes, the actually buffer is set to 8 bytes
26Specifying Synchronous or Asynchronous State
- //Using path, mode, access, sharing permission,
buffer size and specifying asynchronous
operations - FileStream outF new FileStream(C\\Networking\\
MyStream.txt, FileMode.Open, FileAccess.Write,
FileShare.Read, 1000, true)
27File Handle
- A file handle is a unique identifier that the
operating system assigns to a file when the file
is opened or created - A file handle is represented using the IntPrt
structure, which represents an integer of
platform-specific length. - Using the file handle, you may specify several
properties of the stream - //Create FileStream Instance
- FileStream inF new FileStream(
C\Neworking\\MyStream.txt, FileMode.Open) - Get the file Handle
- InterPtr fHanld infHandle
28Streams in .NET
- Synchronous and Asynchronous I/O
- Stream class provides for both synchronous
asynchronous - Stream Class
- FileStream Class
- Reading and Writing with the FileStream Class
- BufferedStream Class
- MemoryStream Class
- NetworkStream Class
- CryptoStream Class
29Reading Writing
- Synchronous I/O
- Stream class
- Asynchronous I/O
30Synchronous I/O
- Stream class
- Read method
- Write method
- Example
- Performs synchronous I/O operations
- Seek method sets the position within the stream
- Need System.IO namespace
- Need System.Text (convert strings to byte arrays)
31Synchronous I/O
- using System
- using System.Collections.Generic
- using System.Text
- using System.IO
- namespace SyncIO
-
- class Program
-
Note additional namespace(s)
32Synchronous I/O
- static void Main(string args)
-
- //Create FileStream instance
- FileStream synF new FileStream("SyncDemo.txt",
FileMode.OpenOrCreate) - //this will open our file if it exists
otherwise a new file is created. -
33Synchronous I/O
- //A character is converted to a byte and then
written in a file using the WriteByte method - //After the byte is written, the file position
is automatically incremented by 1. - Console.WriteLine("--Writebyte Method demo--")
- synF.WriteByte(Convert.ToByte('A'))
34Synchronous I/O
- //Converting a string to a byte array (with the
GetBytes method of the Encoding class in
System.Text - //Write takes three parameters
- // the byte array to write
- // the position or offset in the array from
where to start writing - // the length of data to be written
- Console.WriteLine("--Write method demo--")
- byte writeBytes Encoding.ASCII.GetBytes(" is
the first character.") - synF.Write(writeBytes, 0, writeBytes.Length)
-
35Synchronous I/O
-
- //Reading the data from the file
- //When reading or writing on a FileStream, the
current position(or pointer)of the file
automatically - //increases by the number of bytes read or
written. - //set pointer at origin (start of file or start
of stream) - synF.Seek(0, SeekOrigin.Begin)
- //Now we can read. We'll read a single byte
with the ReadByte method first. - //A byte is read from the stream (with the
position automatically increased by 1) and
converted by to char. - Console.WriteLine("--Readbyte Method demo--")
- //Read byte and display
- Console.WriteLine("First character is -gt "
Convert.ToChar(synF.ReadByte())) -
36Synchronous I/O
-
- //Now we read the remainder of the file with
the Read method. - //This method takes 3 parameters
- // A byte array that will store the data read
- // the position or offset in the array from
where to start reading - // the number of bytes to read
- //Because we want to read all of the remaining
bytes in the file, we want to read in synF.Length
- 1 bytes - //Use of Read method
- Console.WriteLine("--Read Method demo--")
- //Allocate buffer
- byte readBuf new bytesynF.Length - 1
- //Read file
- synF.Read(readBuf, 0, Convert.ToInt32(synF.Length
- 1))
37Synchronous I/O
- //The byte array is then converted to string
using the GetString method of the Encoding Class - //Display contents
- Console.WriteLine("The rest of the file is "
Encoding.ASCII.GetString(readBuf)) - //close the file
- synF.Close()
- Console.WriteLine("Press a key to continue.")
- Console.ReadLine()
-
-
38Asynchronous I/O
- FileStream opens asynchronously when you pass
true to the useAsync flag - A special call-back mechanism is needed to
implement asynchronous I/O, and an AsyncCallback
delegate provides a way for client applications
to implement this call-back mechanism. - This call-back delegate is supplied to the
BeginRead or BeginWrite method
39Asynchronous I/O
- using System
- using System.Collections.Generic
- using System.Text
- using System.IO
- using System.Threading
- namespace AsyncDemo
-
- class Program
-
- //Stream object for reading
- static FileStream fileStrm
- //Buffer to read
- static byte readBuff
40Asynchronous I/O
- //We declare an AsyncCallback delegate field for
the callback function - //AsyncCallback delegate
- static AsyncCallback Callback
- //In the Main method, we initialize our callback
delegate to point to the Callback function method - //This is the method that will be called when
the end of the aynchronous read operation is
signalled
41Asynchronous I/O
- static void Main(string args)
-
- Callback new AsyncCallback(CallBackFunction)
- //now we can initialise our FileStream object,
specifying asynchronous operations - fileStrm new FileStream("Test.txt",
FileMode.Open, FileAccess.Read, FileShare.Read,
64, true) - readBuff new bytefileStrm.Length
- //we can use the BeginRead method to initiate
asynchronous read opeations on the stream. - //The callback delegate is passed to the
BeginRead method as its second-to-last parameter. - //Call async read
- fileStrm.BeginRead(readBuff, 0,
readBuff.Length, Callback, null)
42Asynchronous I/O
- //Data will be read from FileStream while we
continue with other activities. - //Here we simply give the appearance of doing
some other work by looping and every so often
putting the main thread to sleep - //Once the loop has finished, the FileStream
object is closed. - //Simulation of main execution
- for (long i 0 i lt 5000 i)
-
- if (i 1000 0)
-
- Console.WriteLine("Executing in Main - "
i.ToString()) - Thread.Sleep(10)
- //end of if
- //end of for long
- fileStrm.Close()
- Console.WriteLine("Press a key to continue.")
- Console.ReadLine()
- //end of Main
43Asynchronous I/O
- static void CallBackFunction(IAsyncResult
asyncResult) -
- //Gets called when read operation has completed
- int readB fileStrm.EndRead(asyncResult)
- if (readB gt 0)
-
- Console.WriteLine(Encoding.ASCII.GetString(readBu
ff, 0, readB)) - //end of if
- //end of CallBackFunction
-
44Streams in .NET
- Synchronous and Asynchronous I/O
- Stream class provides for both synchronous
asynchronous - Stream Class
- FileStream Class
- Reading and Writing with the FileStream Class
- BufferedStream Class
- MemoryStream Class
- NetworkStream Class
- CryptoStream Class
45Buffered Stream Class
- A buffer is a reserved area of memory used for
storing temporary data. - Its main purpose is to improve I/O performance,
and its often used to synchronise data transfer
between devices of different speeds. Many online
media applications use buffers as intermediate
storage. - BufferedStream Class
- Stream object
- Generally used with .NetworkStream to store data
in memory - FileStream Class has its own internal buffer
- MemoryStream Class does not require buffering
46Buffered Stream Class
- using System
- using System.Collections.Generic
- using System.Text
- using System.IO
- using System.Threading
- namespace BufferedStreamDemo
-
- class Program
-
- static void Main(string args)
-
- FileStream fStr new
FileStream("BufferDemo.txt", FileMode.OpenOrCreate
) - byte writeBytes
Encoding.ASCII.GetBytes("The difference between
genius and stupidity is that genius has its
limits.") - fStr.Write(writeBytes, 0,
writeBytes.Length) - Console.WriteLine("Message written")
- fStr.Seek(0, SeekOrigin.Begin)
- readBufStream(fStr)
- Console.WriteLine("Press a key to
continue")
47Buffered Stream Class
- //Takes a stream object parameters, wraps it in a
buffered stream object and performs a read
operaton - //Reading Buffered Stream
- public static void readBufStream(Stream st)
-
- //Compose BufferedStream
- BufferedStream bf new BufferedStream(st)
- byte inData new Bytest.Length
- //Read and display buffered data
- bf.Read(inData, 0, Convert.ToInt32(st.Length))
- Console.WriteLine(Encoding.ASCII.GetString(inData
)) -
-
-
48Memory Stream Class
- Situation where application needs data frequently
(e.g. lookup table) - Storing data in file
- Cause delays
- Reduce performance of application
- Use MemoryStream Class for cases where data needs
to be stored in memory - MemoryStream Class is used for fast, temporary
storage
49Memory Stream Class
- using System
- using System.Collections.Generic
- using System.Text
- using System.IO
- using System.Threading
- namespace MemoryStreamDemo
-
- class Program
-
- static void Main(string args)
-
- //Create empty Memory stream
- MemoryStream ms new MemoryStream()
- byte memData Encoding.ASCII.GetByt
es("This will go in Memory!") - //Write data
- ms.Write(memData, 0, memData.Length)
50Memory Stream Class
- //Set pointer at origin
- ms.Position 0
- byte inData new byte100
- //Read memory
- ms.Read(inData, 0, 100)
- Console.WriteLine(Encoding.ASCII.GetSt
ring(inData)) - Stream str new FileStream("MemOutput
.txt", FileMode.OpenOrCreate, FileAccess.Write) - ms.WriteTo(str)
- str.Close()
-
-
-
51Network Stream Class
- NetworkStream class is in the System.Net.Sockets
namespace - Unbuffered stream
- Does not support random access to data
- BufferedStream class is often used to buffer the
NetworkStream
52Properties of Network Stream
53Network Stream Class
- Each NetworkStream constructor requires at least
one Socket. - A NetworkStream object can be retrieved from a
TcpClient
54Network Stream Example (Listener)
- using System
- using System.Collections.Generic
- using System.Text
- using System.Net
- using System.IO
- using System.Net.Sockets
- namespace TCPListenerDemo
-
- class Program
-
- static void Main(string args)
-
- try
-
- //Create TCP Lister to listen on
port 5001 - IPAddress ipAddress
Dns.GetHostEntry("localhost").AddressList0 - TcpListener listener new
TcpListener(ipAddress, 5001) -
55Network Stream Example (Listener)
- //Start listening
- listener.Start()
- //AcceptClient accepts a
connection request, returning a TcpClient - TcpClient tc listener.AcceptTcpC
lient() - //we use the TcpClient's
GetStream to create a NetworkStream object - NetworkStream stm
tc.GetStream() - //now we can read data as we have
with the other streams, using the Read method - byte readBuf new byte100
- stm.Read(readBuf, 0, 100)
- //Display data
- Console.WriteLine(Encoding.ASCII.G
etString(readBuf)) - stm.Close()
- //end of try
- catch (Exception ex)
-
- Console.WriteLine(ex.ToString())
- //end of catch
-
-
56Network Stream Client
- using System
- using System.Collections.Generic
- using System.Text
- using System.Net
- using System.IO
- using System.Net.Sockets
- namespace TCPClient
-
- class Program
-
- static void Main(string args)
-
- try
-
- //Create TCP Client
- TcpClient client new
TcpClient()
57Network Stream Client
- //Connect using hostname and port
- client.Connect("localhost",
5001) - //Get network stream instance for
sending data - NetworkStream ns
client.GetStream() - //Now that we have our
NetworkStream, sending data follows the same
process as we've used with the other streams - byte sendBytes
Encoding.ASCII.GetBytes("This data has come from
another place!") - ns.Write(sendBytes, 0,
sendBytes.Length) - //Finally, close our client
- client.Close()
- //end of try
- catch (Exception ex)
-
- Console.WriteLine(ex.Message)
- Console.WriteLine("The listener
has probably not started.") - //end of catch
-
-
58CryptoStream Class
- Secure data
- Encrypt/decrypt with secret key
- CryptoStream derives from Stream class
- CryptoStream constructor takes 3 parameters
- Stream to be used
- Cryptographic transformation
- Specific read/write access to the cryptographic
stream - Any cryptographic service provider that
implements the ICryptoTransform interface can be
used
59CryptoStream Class
- using System
- using System.Collections.Generic
- using System.Text
- using System.IO
- using System.Security.Cryptography
- namespace cryptDemo
-
- class Program
-
- static void Main(string args)
-
- SymmetricAlgorithm des null
- int answer Menu(ref des)
- //A file stream is created to save
encrypted data - FileStream fs new
FileStream("SecretFile.dat", FileMode.Create,
FileAccess.Write) - //The interface helps define the
basic operation of our cryptographic
transformation - ICryptoTransform desencrypt
des.CreateEncryptor() - //Wrap cryptoStream around fileStream
60CryptoStream Class
- //Write byte array to cryptoStream
- cryptoStream.Write(byteArrayInput, 0,
byteArrayInput.Length) - cryptoStream.Close()
- fs.Close()
- //Time to
Decrypt// - //Create file stream to read
encrypted file back - FileStream fsRead new
FileStream("SecretFile.dat", FileMode.Open,
FileAccess.ReadWrite) - byte encByte new
bytefsRead.Length - fsRead.Read(encByte, 0,
encByte.Length) - Console.WriteLine("Encrypted Message
0", Encoding.ASCII.GetString(encByte)) - //set the position of the within the
filestream back to 0 before decrypting - fsRead.Position 0
- //Create DES Decryptor from our des
instance - ICryptoTransform desdecrypt
des.CreateDecryptor() - CryptoStream cryptoStreamDecr new
CryptoStream(fsRead, desdecrypt,
CryptoStreamMode.Read) - byte decrByte new
bytefsRead.Length - cryptoStreamDecr.Read(decrByte, 0,
(int)fsRead.Length) - string output Encoding.Unicode.GetSt
ring(decrByte)
61CryptoStream Class
- private static int Menu(ref SymmetricAlgorithm
des) -
- bool isCorrect true
- int answer 0
- //Ask the user to choose a service
provider - //All service providers derived from
the SymmetricAlgorithm class have a single secret
key that is used for both encrypting and
decrypting - do
-
- isCorrect true
- Console.WriteLine("Select Service
Provider for CryptoStream") - Console.WriteLine("1
DESCryptoServiceProvider") - Console.WriteLine("2
RC2CryptoServiceProvider") - Console.WriteLine("3
RijndaelManaged") - Console.WriteLine("4
TripleDESCryptoServiceProvider") - Console.WriteLine("5
SymmetricAlgorithm") - Console.Write("Enter your choice
") - //create des object
- switch (Console.ReadLine())
62CryptoStream Class
- answer 2
- break
- case "3" des new
RijndaelManaged() - answer 3
- break
- case "4" des new
TripleDESCryptoServiceProvider() - answer 4
- break
- case "5" des
SymmetricAlgorithm.Create() - answer 5
- break
- default
-
- Console.WriteLine("Wro
ng Selection") - isCorrect false
- break
- //end of default
- //end of switch
- while (!(isCorrect))
63Basic Outline
- Streams in .NET
- Stream Manipulation
- Introduction
- Encoding String Data
- Binary Files
- Text Reader
- Text Writer
- Serialisation
64Stream Manipulation
- System.IO namespace provides classes and methods
for manipulating different data types in streams
65Encoding String Data
- Without knowing what the bytes mean, transmitted
data is meaningless - Encoding Class in System.Text
- Handles UNICODE characters
66Encoding Classes and Uses
67Encoding Class Methods
68Encoding Class Methods
69Encoding String Data
- using System
- using System.Text
- using System.IO
- namespace EncodingStringData
-
- class Program
-
- static void Main(string args)
-
- string test "This is our test
string." - byte asciiBytes
- byte unicodeBytes
- byte UTF7Bytes
- //convert our test string into the
three different encodings - asciiBytes Encoding.ASCII.GetBytes(t
est) - Console.WriteLine("ASCII Byte
String")
70Encoding String Data
- unicodeBytes Encoding.Unicode.GetBytes(
test) - Console.WriteLine("Unicode Byte
String") - Console.WriteLine("Unicode Encoding
0 bytes", unicodeBytes.Length) - DisplayArray(unicodeBytes)
- Console.WriteLine("Effect of
converting to Unicode") - string unicodeString
Encoding.ASCII.GetString(unicodeBytes) - Console.WriteLine(unicodeString)
- Console.WriteLine()
- UTF7Bytes Encoding.UTF7.GetBytes(tes
t) - Console.WriteLine("UTF7 Byte
String") - Console.WriteLine("UTF7 Encoding 0
bytes", UTF7Bytes.Length) - DisplayArray(UTF7Bytes)
- Console.WriteLine("Effect of
converting to UTF7") - string utf7String
Encoding.ASCII.GetString(UTF7Bytes) - Console.WriteLine(utf7String)
- Console.WriteLine()
71Encoding String Data
- static void DisplayArray(byte b)
-
- for (int i 0 i lt b.Length i)
- Console.Write(bi " ")
- Console.WriteLine()
- //end of DisplayArray
-
-
72Basic Outline
- Streams in .NET
- Stream Manipulation
- Introduction
- Encoding String Data
- Binary Files
- BinaryReader
- BinaryWriter
- Text Reader
- Text Writer
- Serialisation
73Binary Files
- System.IO namespace contains
- BinaryReader
- BinaryWriter
- Used for working with primitive data types from
streams - Each class is created around an existing Stream
74BinaryReader
- Default is UTF-8 encoding
- Custom encoding is possible (at instantiation)
- BinaryReader
- Read
- Read bytes from the stream and advances the
position in the stream, returning -1 if the end
of the stream is reached - PeekChar
- To read without advancing the position in the
stream - Returns -1 if the end of the stream is reached or
if the stream does not support seeking
75Binary Reader Methods
76Binary Reader Methods
77 Binary Writer
- Used for writing primitive types in binary format
to a stream - Writing to the stream is achieved with the Write
method. - To move around the stream, the Seek method sets
the position in the Stream as with the Seek
method of the Stream. - Standard management methods utilised
- Close
- Flush
78Binary Reading and Writing Example
- using System
- using System.IO
- namespace BinaryReaderAndWriter
-
- class Program
-
- static void Main(string args)
-
- double angle, sinAngle
- //Create a file stream called fStream
that creates a file called "Sines.dat" - //Stream specifies write access
- FileStream fStream new
FileStream("Sines.dat", FileMode.Create,
FileAccess.Write) - BinaryWriter bWriter new
BinaryWriter(fStream) - //We calculate the sine of angles
between 0 and 90 degrees at 5 degree intervals - //We have to convert the angle in
degrees to radians before we can calculate the
sine - //Then we use Write to output these
values to the stream - for (int i 0 i lt 90 i 5)
79Binary Reading and Writing Example
- //----------Reading from
File-------------- - FileStream fStrm new
FileStream("Sines.dat", FileMode.Open,
FileAccess.Read) - BinaryReader bReader new
BinaryReader(fStrm) - int endOfFile
- //use the ReadDouble method to read
the data back in - //If this method tries to read beyond
hte end of the stream, an exception will be
thrown, - //so we use the PeekChar method to
detect the end of the file without advancing the
position - do
-
- endOfFile bReader.PeekChar()
- if (endOfFile ! -1)
-
- angle bReader.ReadDouble()
- sinAngle bReader.ReadDouble(
) - Console.WriteLine("0
1", angle, sinAngle) - //end of if
- while (endOfFile ! -1)
- bReader.Close()
80Basic Outline
- Streams in .NET
- Stream Manipulation
- Introduction
- Encoding String Data
- Binary Files
- Text Reader
- Working with StreamReader
- Text Writer
- Working with StreamWriter
- Serialisation
81Text Reader
- Used for reading text or characters in a stream
- Its an abstract class from which StreamReader
and StringReader derive - The text is read in by a StringReader is stored
as a StringBuilder, rather than a plain string
82TextReader Class Methods
83TextReader Class Methods
84Working with StreamReader
- Used to read characters from a byte stream
- Default is UTF-8 encoding
- Provides forward-only access to the stream
85Example
- public static string fileName _at_"TextOut.txt"
- static void Main(string args)
-
- Stream fs new FileStream(fileName,
FileMode.Open, FileAccess.Read) - //Using Stream Object
- StreamReader sReader new StreamReader(fs)
- string data
- int line 0
- while ((data sReader.ReadLine()) ! null)
-
- Console.WriteLine("Line 0 1 Position
2", line, data, sReader.BaseStream.Position) - //sReader.DiscardBufferedData()
-
- //Set position using seek property of underlying
stream - sReader.BaseStream.Seek(0, SeekOrigin.Begin)
- Console.WriteLine()
86TextWriter
- Abstract class
- Outputs a sequential series of characters
- StreamWriter and StringWriter are derived from
TextWriter
87TextWriter Class Methods
88TextWriter Class Methods
89Working with StreamWriter
- Used for writing characters in a stream
- Default is UTF-8 Encoding
- StreamWriter constructor is overloaded
- Can pass a stream object to a StreamWriter (gives
greater control over file accessibility)
90StreamWriter
- static void Main(string args)
-
- string s1 "The length of a film should be
directly related to the endurance of the human
bladder. - Alfred Hitchcock." - string s2 "USA Today has come out with a new
survey Apparently three out of four people make
up 75 percent of the population.-David
Letterman." - Stream fs new FileStream("TextOut.txt",
FileMode.OpenOrCreate, FileAccess.Write) - //Using Stream Object
- StreamWriter sWriter new StreamWriter(fs)
- //Display the encoding type
- Console.WriteLine("Encoding Type 0",
sWriter.Encoding.ToString()) - //Display Format Provider
- Console.WriteLine("Format Provider 0",
sWriter.FormatProvider.ToString()) - sWriter.WriteLine("Today is 0.",
DateTime.Today.DayOfWeek) - sWriter.WriteLine(s1)
- sWriter.WriteLine(s2)
91StreamWriter
- for (int i 0 i lt 5 i)
-
- sWriter.WriteLine("Value 0, its square is
1.", i, i i) - //end of for
- //Writing array
- sWriter.Write("Arrays can be written ")
- char myArray new char 'a', 'r', 'r',
'a', 'y' - sWriter.Write(myArray)
- sWriter.WriteLine("\r\nAnd parts of arrays can
be written.") - sWriter.Write(myArray, 0, 3)
- sWriter.Close()
- fs.Close()
- Console.WriteLine("Press a key to continue.")
- Console.ReadLine()
92Basic Outline
- Streams in .NET
- Stream Manipulation
- Introduction
- Encoding String Data
- Binary Files
- Text Reader
- Text Writer
- Serialisation
- Serialising into XML Format
- Serialising with Formatter Objects
93Serialisation
- Serialisation is the process of taking objects
and converting their state information into a
form that can be stored or transported. - The stored or transported object can then be
de-serialised to re-create the original state of
object. - Key areas where serialisation is beneficial
- Object availability A component can be saved in
a file made available whenever required - Object lifetime Saving the object with its state
increases its life. In normal practice, when you
close an application, all associated objects are
destroyed automatically - Object use within networked applications The
complex form of the object has been transformed
to a format that is suitable for transferring
across a network and possibly through firewalls - Object reliability The saved object can be
re-created as is.
94Serialising into XML format
- XML has advantages
- Transform system-specific state information into
text (which is easily transported over a network) - XML disadvantage
- Does not preserve the type of the various fields
involved (it serialises properties/fields into
XML format) - XMLSerializer class in System.XML.Serialization
namespace - Rules for serializing a class
- The class must support a default public
constructor with no parameters - Only public properties that support both get and
set operations and public data members are
persisted
95Serialisation using XML
- The Customer class
- public class Customer
-
- public int CustomerID
- public string CustomerName
- public DateTime SignUpDate
- private decimal currentCredit
- public void SetCurrentCredit(decimal c)
-
- currentCredit c
-
- public decimal GetCurrentCredit()
-
- return currentCredit
-
- //end of Customer
Notice the public and private fields
96Serialising Customer to XML
- using System
- using System.IO
- using System.Text
- using System.Xml.Serialization
- static void Main(string args)
-
- //prepare object for serialisation
- Customer cm new Customer()
- cm.CustomerID 12
- cm.CustomerName "Stuart Little"
- cm.SignUpDate DateTime.Now
- cm.SetCurrentCredit(76.23M)
- Console.WriteLine("Now Serialising...")
- //Create Stream Writer object
- StreamWriter writer new StreamWriter("Customer
.xml") - //Create Serialiser
- XmlSerializer serializer new
XmlSerializer(typeof(Customer)) - //Serialise the object
97Serialising an object
-
- Console.WriteLine("Now Deserialising...")
- //Open and create stream
- Stream streamOut new FileStream("Customer.xml",
FileMode.Open, FileAccess.Read) - XmlSerializer deserial new XmlSerializer(typeo
f(Customer)) - //Deserialise the sotred stream
- Customer recm (Customer)deserial.Deserialize(
streamOut) - streamOut.Close()
- //Display sate of object
- Console.WriteLine("Customer ID 0",
recm.CustomerID) - Console.WriteLine("Customer name 0",
recm.CustomerName) - Console.WriteLine("Sign up Date 0",
recm.SignUpDate) - Console.WriteLine("Current Credit 0",
recm.GetCurrentCredit()) - Console.ReadLine()
98Serialising with Formatter Objects
- Within the System.Runtime.Serialization.Formatters
namespace lie the tools for serializing object
state into formats such as binary or SOAP - The BinaryFormatter class provides functionality
for serializing objects into binary format, and
the SoapFormatter class serialises into the SOAP
format - Binary format serialises object state and also
assembly information allowing exact reproduction
of an object and its types. It also produces a
compact format - The SOAP format is more verbose (wordy), but it
allows your object state to be passed to a web
service
99The Steps for serialising an object/class
- Mark the class with the Serializable attribute
to make it serializable - Prepare the objects state for serialization
- Create a new formatter object BinaryFormatter
for binary format or SoapFormatter for SOAP - Call the Serialize method of the formatter
object, passed in the stream to which to output
the results and the object to be serialized
100Deserializing
- Specify the format for deserializing the object
with the relevant formatter object - Call the Deserialize method of this formatter
object - Cast the object returned to the type you wish to
re-create
101Serializing
- The Serializable attribute is not inherited,
thus derived types are not automatically
serialisable. - To protect confidential data, you can make a
field NonSerialized any such fields will not
be serialised (says the book need further
testing to verify)
102Summary