Programming C#

Florian Rappl, Department of Theoretical Physics, University of Regensburg

Programming C#

Day 5: IO, webrequests, events, serializing objects and dynamic types


  • Accessing the file system
  • Streams
  • Performing web requests
  • The C# event system
  • Serializing data in C#
  • The XML serializer
  • Dynamic programming with C#
  • object, var and dynamic

Accessing the file system

  • Task: Get information about a directory
  • Or tell me everything about a file
  • We need to read out information of the FS
  • Luckily Windows knows everything and has good APIs
  • The .NET-Framework opens those APIs for us
  • Important: When handling files think about threading
  • We do not want to block the UI thread

The System.IO namespace

  • The static helper class Path
  • Two important classes: Directory and File
  • Encapsulations like DirectoryInfo, FileInfo
  • Or more specialized DriveInfo
  • All kinds of streams (memory, file, text, ...)
  • The whole ACL model

→ Example - The file system


  • Usually every IO operation is about streaming data
  • Every stream of data is dependent of the corresponding device
  • e.g. HDD, RAM, ethernet, modem, ...
  • The abstract base class is Stream
  • Sometimes it might make sense to implement it yourself
  • Reading a file has to do with streams

Reading a file

  • A specific implemention called FileStream exists
  • var fs = new FileStream("...", FileMode.Open) will give us the stream
  • Now we can read a byte with ReadByte()
  • Read() will read as many bytes as specified into an array
  • Returns the number of read bytes (the end of the stream is a barrier)

Writing a file

  • Writing a file is quite similar - e.g. FileMode.Create
  • Here we have methods like WriteByte() and Write()
  • Very important: After our operations we have to close the file
  • This happens with the method Close()
  • Depending on the device bytes could be buffered before any actual write
  • If immediate writing is required use the Flush() method
  • Always use ReadAsync() and WriteAsync()

StreamReader, StreamWriter

  • They are implementations of TextReader, TextWriter
  • Their purpose is elegant handling of text
  • They expect a Stream (or create a FileStream)
  • One can set a proper text encoding (like UTF8, Unicode, ...)
  • e.g. var sw = new StreamWriter("...", false, Encoding.ASCII)
  • Here we have additionally WriteLine()
  • All write methods accept strings or convert objects to strings

→ Example - Memory and file streams

Web requests

  • Accessing the internet is quite easy
  • WebRequest.Create() creates a new web request
  • Here not blocking the UI is very important
  • We can directly query URLs and more
  • Direct access to the request stream (to the server)
  • We first need to request a response object
  • Then the request is completed
  • The response stream (answer) is then received (from the server)

A simple web request

var request = WebRequest.Create(url);
var response = await request.GetResponseAsync();
var stream = new StreamReader(response.GetResponseStream());
var content = stream.ReadToEnd();

→ Example - A webrequest with C#


The C# event system

  • Important: The event keyword
  • Events are just delegates, but with benefits
  • Only accessible with the +=, -= operations (outside)
  • Inside we can execute them (called firing)
  • public event EventHandler MyEvent to register
  • The delegate in this example is EventHandler
  • .NET pattern: Arguments object, EventArgs (or derived)
  • The return type should be void

Important event facts

  • Firing an event is done in the current thread
  • If necessary: perform context switch
  • If the handler is not set, it will be null (check first!)
  • One should prefer using overrides instead of events
  • This is of course only possible when deriving from a class
  • Events are (mostly) fired synchronously

→ Example - Events

Serializing data

  • The BitConverter is a very useful class
  • The attribute [Serializable] is important
  • Two ways: objects to bytes and bytes to objects

XML serialization

  • Another way is the XML serialization
  • Advantage: Human readable and standardized
  • Disadvantage: Big files with overhead
  • Just use the XmlSerializer class
  • The method for serializing is Serialize()
  • Object creation from XML files is also possible
  • Here we have to use the Deserialize() method

→ Example - Object serialization

Dynamic programming

  • C# and the CLR are static typed
  • However, the DLR (Dynamic Language Runtime) is not
  • C# introduces the DynamicObject type
  • This is our portal to the DLR
  • We have to tell the compiler explicitely to use dynamic
  • How to use? dynamic a = 4


  • Easier interaction with dynamic languages
  • Here mostly JavaScript and Python are mentioned
  • However, we lose intellisense support
  • The compiler cannot detect errors
  • Be aware of possible exceptions during runtime

→ Example - Dynamic


object, var and dynamic

  • Never think they are equal!
  • var can be object or dynamic
  • var is no type, but a placeholder
  • object is the most general type; everything is an object
  • dynamic is no type, but a switch
  • It tells the compiler to use the DLR

All available presentations

More questions? Just mail!


Florian Rappl, MVP Visual C#