Nikolay Kostov (Nikolay.IT)
Topics covered:
- What is Stream?
- Reading Text Files
- Writing Text Files
- Handling I/O Exceptions
Video (in Bulgarian)
Presentation Content
What Is Stream?
- Stream is the natural way to transfer data in the computer world
- To read or write a file, we open a stream connected to the file and access the data through the stream
Streams Basics
- Streams are used for reading and writing data into and from devices
- Streams are _ordered sequences of _ bytes
- Provide consecutive access to its elements
- Different types of streams are available to access different data sources:
- File access, network access, memory streams and others
- Streams are open before using them and closed after that
The StreamReader Class
- System.IO.StreamReader
- The easiest way to read a text file
- Implements methods for reading text lines and sequences of characters
- Constructed by file name or other stream
- Can specify the text encoding
- For Cyrillic use UTF8
- Works like Console.Read() / ReadLine() but over text files
StreamReader Methods
- _new _ StreamReader(fileName)
- Constructor for creating reader from given file
- ReadLine()
- Reads a single text line from the stream
- Returns null when end-of-file is reached
- ReadToEnd()
- Reads all the text until the end of the stream
- Close()
Using StreamReader – Practices
- The StreamReader instances should always be closed by calling the Close() method
- Otherwise system resources can be lost
- In C# the preferable way to close streams and readers is by the " using " construction
- It automatically calls the Close() after the using construction is completed
The StreamWriter Class
- System.IO.StreamWriter
- Similar to StreamReader , but instead of reading, it provides writing functionality
- Constructed by file name or other stream
- Can define encoding
- For Cyrillic use "UTF8 "
StreamWriter Methods
- Write ()
- Writes string or other object to the stream
- Like Console.Write ()
- WriteLine ()
- Like Console.Write Line()
- Flush ()
- Flushes the internal buffers to the hard drive
- AutoFlush
- Flush the internal buffer after each writing
What is Exception?
- "An event that occurs during the execution of the program that disrupts the normal flow of instructions“ – definition by Google
- Occurs when an operation can not be completed
- Exceptions tell that something unusual has happened, e. g. error or unexpected event
- I/O operations throw exceptions when operation cannot be performed (e.g. missing file)
- When an exception is thrown, all operations after it are not processed
Summary
- Streams are the main I/O mechanismsin .NET
- The StreamReader class and ReadLine() method are used to read text files
- The StreamWriter class and WriteLine() method are used to write text files
- Always put file handling in using(…) block
- Exceptions are unusual events or error conditions
- Can be handled by try-catch-finally blocks