Byte Writing Reading - CSharp File IO

CSharp examples for File IO:Binary File

Description

Byte Writing Reading

Demo Code

using System;//from  ww w .  j  a  va  2 s.  c  o m
using System.IO;
class Tester
{
   public static void WriteBytes()
   {
      FileStream outStream = null;
      try
      {
         FileInfo bytesFile = new FileInfo(@"C:\temp\numbers1.dat");
         outStream = bytesFile.OpenWrite();
         for (byte i = 0; i < 10; i++)
         {
            outStream.WriteByte(i);
         }
      }
      catch (IOException exObj)
      {
         Console.WriteLine(exObj);
      }
      finally
      {
         outStream.Close();
      }
   }
   public static void ReadBytes()
   {
      int totalSum = 0;
      int temp;
      FileStream inStream = null;
      try
      {
         FileInfo numberFile = new FileInfo(@"C:\temp\numbers1.dat");
         inStream = numberFile.OpenRead();
         Console.WriteLine("Length: " + inStream.Length);
         Console.WriteLine("List of numbers in file:");
         for (int i = 0; i < inStream.Length; i++)
         {
            temp = inStream.ReadByte();
            Console.WriteLine(temp);
            totalSum += temp;
         }
         Console.WriteLine("\nTotal sum of numbers in file: {0}", totalSum);
      }
      catch (IOException exObj)
      {
         Console.WriteLine(exObj);
      }
      finally
      {
         inStream.Close();
      }
   }
   public static void Main()
   {
      WriteBytes();
      ReadBytes();
   }
}

Result


Related Tutorials