Streams

  1. Read, which is the transfer of data from a stream into a data structure, such as an array of bytes.
  2. Write, which is the transfer of data from into a stream.
  3. Streams can support seeking.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0de90720-cf53-4c4b-be4b-d880a81b5e5d/Untitled

var originalInstance = new MyObject();
IFormatter formatter = new BinaryFormatter();

// Serialization
byte[] bytes;
using (var writeStream = new MemoryStream())
{
    formatter.Serialize(writeStream, originalInstance);
    bytes = writeStream.ToArray();
}

// Deserialization
using (var readStream = new MemoryStream(bytes))
{
    var deserializedInstance = (MyObject) formatter.Deserialize(readStream);
}

Encoding and Decoding

FileStream Class

const string filePath = "MyTest.txt";
using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    // Write into the file stream.
    var bytesToWrite = Encoding.UTF8.GetBytes("Test String...");
    fileStream.Write(bytesToWrite, 0, bytesToWrite.Length);
}

using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    // Read the written data from the file stream.
    var bytesBuffer = new byte[fileStream.Length];
    fileStream.Seek(0, SeekOrigin.Begin);
    var bytesToRead = bytesBuffer.Length;
    var bytesRead = 0;
    while (bytesToRead > 0)
    {
        var resultedBytes = fileStream.Read(bytesBuffer, bytesRead, bytesToRead);
        if (resultedBytes == 0) // No bytes remained to read.
            bytesToRead = 0;
        else
        {
            bytesRead += resultedBytes;
            bytesToRead -= resultedBytes;
        }
    }
    var outputString = Encoding.UTF8.GetString(bytesBuffer);
}

File Class Utilities

const string filePath = "MyTest.txt";

using (FileStream fileStream = File.OpenRead(filePath))
{
    var bytesBuffer = new byte[fileStream.Length];
    for (var i = 0; i < fileStream.Length; i++)
        bytesBuffer[i] = (byte)fileStream.ReadByte();
}

using (StreamReader streamReader = File.OpenText(filePath))
{
    var fileContent = streamReader.ReadToEnd();
}

// You can use this approach to read the file content line by line.
using (StreamReader streamReader = File.OpenText(filePath))
{
    while (!streamReader.EndOfStream)
    {
        var lineContent = streamReader.ReadLine();
    }
}

using (StreamWriter streamWriter = File.CreateText(filePath))
{
    streamWriter.WriteLine("Line 1");
    streamWriter.Write("Line 2");
}

Using Different Types of Streams Together