Sunday 14 May 2017

Streams 02 FileStream

File streams are used to read and write data to and from files

using System;
using System.IO;
using System.Text;

namespace pc.FileStreamExample {
    class Program {
        static void Main(string[] args) {
            byte[] outArray = Encoding.Default.GetBytes("hello world this is a test");
            byte[] inArray = new byte[outArray.Length];

            using (FileStream fs = new FileStream(@"c:\temp\myFile.txt",
                   FileMode.Create, FileAccess.ReadWrite)) {
                try {
                    //write outArray content to file
                    fs.Write(array: outArray, offset:0, count: outArray.Length);
                    //reset file position
                    fs.Position = 0;

                    //itterate over fs stream and load values into inarray
                    //offseting them by 32 changing uppercase to lowercase
                    for (int i = 0; i < fs.Length; i++)
                        inArray[i] = (byte)(fs.ReadByte() - 32);

                    Console.WriteLine(Encoding.Default.GetString(inArray));
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }
                finally {
                    fs.Close();
                }
            }  
        }
    }
}


The only thing to really remember is that streams work with byte arrays.