Streams and Text Files
Telerik Academy Alpha

 

 Table of contents

What is a stream?

 What is a stream?

  • A stream is an abstraction of a sequence of bytes.

    • Can be accessed in sequential order (pipe with water flowing through it)

      • ​Text files, Images, Network access

  • Two main streams

    • Input stream (read data)

    • Output stream (write date)

  • System.IO namespace in C#

 What is a stream?

Program

Input stream

Output stream

Input Source (keyboard, file, network, etc.)

Output Sink (console, file, network, etc.)

 What is a stream?

  • Stream must be open when needed 
    • and closed when you don't need it anymore
  • It is the programmer responsibility
    • can be done with using() block
Stream fileStream = new FileStream("../../../test.jpg", FileMode.Open, FileAccess.Read);

// Do some operations with the file stream
// Close the stream
fileStream.Close();

// The stream is automatically closed
using (fileStream = new FileStream("../../../test.jpg", FileMode.Open, FileAccess.Read))
{
    // Do some operations with the file stream
}

File streams, readers, writers

 File streams

  • With FileStream you can read/write bytes from file

 

// Write new string to file
string str = "Telerik Academy Alpha";
using(FileStream fileStream = new FileStream("../../../test.txt", FileMode.Open))
{
    for (int i = 0; i < str.Length; i++)
    {
        fileStream.WriteByte((byte)str[i]);
    }
}

// Read all chars
using (FileStream fileStream = new FileStream("../../../test.txt", FileMode.Open))
{
    for (int i = 0; i < fileStream.Length; i++)
    {
        Console.Write((char)fileStream.ReadByte());
    }
}

 File streams and writers/readers

  • StreamReader/Writer vs FileStream

    • streams handle bytes

    • readers/writers handle characters

var reader = new StreamReader("../../../test.txt");
Console.WriteLine((char)reader.Read()); // output: T

// Should close it before using it again below
// Otherwidse the file will be in use
reader.Close();

FileStream fileStream = new FileStream("../../../test.txt", FileMode.Open);
Console.WriteLine((char)fileStream.ReadByte()); // output: T

fileStream.Close();

 Readers/writers

  • StreamReader/Writer 

    • Reader (byte[] to string)

    • Writer (string to byte[])

using (var reader = new StreamReader("../../../test.txt"))
{
    Console.WriteLine(reader.ReadLine()); // Telerik Academy
    // More methods: reader.ReadToEnd();
}

using (var writer = new StreamWriter("../../../test.txt"))
{
    writer.WriteLine("Telerik Academy Alpha"); // Writes to text file
    // More methods: writer.Write();
}

 Combine them

  • Combine Stream and StreamReader/Writer

    • StreamReader/Writer accepts stream or path

using (FileStream fileStream = new FileStream("../../../test.txt", FileMode.Open))
{
    var reader = new StreamReader(fileStream);
    Console.WriteLine(reader.ReadLine()); // Telerik Academy
}

Files

Text Files

 TextFiles

  • You could read or write text files with wrappers over a stream

  • Both StreamReader/Writer and File classes are wrappers over streams

  • Both could read all lines of text from a file

    • StreamReader/Writer gives more control

      • It could read/write file without loading the whole file

    • File makes your code shorter and more understandable

 TextFiles

using (StreamReader reader = new StreamReader("../../../test.txt"))
{
    Console.WriteLine(reader.ReadToEnd());
}

Console.WriteLine(File.ReadAllText("../../../test.txt"));
  • Below code is reading all the text from a file with the two options 

    • StreamReader

    • File

 TextFiles

  • StreamReader/Writer could read/write to/from files line by line

    • This is very useful for certain situations

  • You should choose which class to use (File or StreamReader/Writer) depending on your code requirements

  • There is no right or wrong

Other Files

 Copy file

// Copy an image
// This reads the file as a byte array
// You could use any other method or class
byte[] arr = File.ReadAllBytes("../../../test.jpg");

// This writes the file to the file system
File.WriteAllBytes("../../../test-copy.jpg", arr);
  • You can copy any file 

    • Image

    • Text file

    • pdf

    • etc.

 Modify file

// This will read the file as byte[]
// then it will save another file with bytes only at the even positions
// if the file is an image/pdf or another type of file it will be corrupted
// but if it is a text file it will have missing parts

byte[] arr = File.ReadAllBytes("../../../test.pdf");
List<byte> list = new List<byte>();

for (int i = 0; i < arr.Length; i++)
{
    if (i % 2 == 0)
    {
        list.Add(arr[i]);
    }
}

File.WriteAllBytes("../../../test-part.pdf", list.ToArray());

Questions?

[C#] Streams and files

By telerikacademy

[C#] Streams and files

  • 970