c# stream code example

Example 1: stream deflator c#

using System;
using System.IO;
using System.IO.Compression;

public class Program
{
    public static void Compress(DirectoryInfo directorySelected)
    {
      using (FileStream compressedFileStream = File.Create(file.FullName + ".cmp"))
      {
        using (DeflateStream compressionStream = new DeflateStream(compressedFileStream, CompressionMode.Compress))
        {
          originalFileStream.CopyTo(compressionStream);
        }
      }
    }

    public static void Decompress(FileInfo fileToDecompress)
    {
      using (FileStream decompressedFileStream = File.Create(newFileName))
      {
        using (DeflateStream decompressionStream = new DeflateStream(originalFileStream, CompressionMode.Decompress))
        {
          decompressionStream.CopyTo(decompressedFileStream);
          Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
        }
      }
    }
}

Example 2: c# read file stream

//this will get a string with all the text from the file
var fileText = File.ReadAllText(@"path\to\my\file.txt");

//this will get all of the lines of the file as an string[]
var fileLines = File.ReadAllLines(@"path\to\my\file.txt");

Example 3: C# Stream

private static void SplitFile(string inputFile, int chunkSize, string path)
    {
        byte[] buffer = new byte[chunkSize];
        List<byte> extraBuffer = new List<byte>();

        using (Stream input = File.OpenRead(inputFile))
        {
            int index = 0;
            while (input.Position < input.Length)
            {
                using (Stream output = File.Create(path + "\\" + index + ".csv"))
                {
                    int chunkBytesRead = 0;
                    while (chunkBytesRead < chunkSize)
                    {
                        int bytesRead = input.Read(buffer,
                                                   chunkBytesRead,
                                                   chunkSize - chunkBytesRead);

                        if (bytesRead == 0)
                        {
                            break;
                        }

                        chunkBytesRead += bytesRead;
                    }

                    byte extraByte = buffer[chunkSize - 1];
                    while (extraByte != '\n')
                    {
                        int flag = input.ReadByte();
                        if (flag == -1)
                            break;
                        extraByte = (byte)flag;
                        extraBuffer.Add(extraByte);
                    }

                    output.Write(buffer, 0, chunkBytesRead);
                    if (extraBuffer.Count > 0)
                        output.Write(extraBuffer.ToArray(), 0, extraBuffer.Count);

                    extraBuffer.Clear();
                }
                index++;
            }
        }
    }