File Handling in C#

Text Files

StreamWriters and StreamReaders make it easy to save strings in files and to retrieve them, as shown in this example. The text file ints5.txt will be saved in the same folder as the executable. A copy of the output follows the code.

using System;
using System.IO;

namespace while_file
{
  static class Program
  {
    public static void Main(string[] args)
    {
      StreamWriter sw = new StreamWriter("ints5.txt");
      for (int i = 1; i < 6; i++)
        sw.WriteLine(i.ToString());
      sw.Close();

      StreamReader sr = new StreamReader("ints5.txt");
      String line = "";
      int temp, sum; 
      sum = 0;
      while (line != null)
      {
        line = sr.ReadLine();
        Console.WriteLine(line);
        int.TryParse(line, out temp);
        sum += temp;
      }
      sr.Close();
      Console.WriteLine("Sum: " + sum.ToString());
      Console.ReadLine();
    }
  }
}

Output:
1
2
3
4
5

Sum: 15

Binary Files

Using a BinaryWriter and BinaryReader enables you to save mixed data types to a binary file and to read them in the order that the data items were saved.

using System;
using System.IO;

namespace random_access_dot_net_cs
{
  static class Program
  {
    public static void Main(string[] args)
    {      
      String  myString = "test";
      Char myChar = 'a'; //single quotes
      Double myDouble = 12.345;
      int myInt = 42;
      Int64 myInt64 = 123456789;
      FileStream fs;
      BinaryWriter bw;
      BinaryReader br;
      fs = new FileStream("test.bin", FileMode.Create, FileAccess.Write);
      bw = new BinaryWriter(fs);
      bw.Write(myString);
      bw.Write(myChar);
      bw.Write(myDouble);
      bw.Write(myInt);
      bw.Write(myInt64);
      bw.Close();
      fs.Close();
      fs = new FileStream("test.bin", FileMode.Open , FileAccess.Read);
      br = new BinaryReader(fs);   
      String myString2 = br.ReadString().ToString();
      Console.WriteLine(myString2);
      Char myChar2 = br.ReadChar();
      Console.WriteLine(myChar2);
      Double myDouble2 = br.ReadDouble();
      Console.WriteLine(myDouble2);
      int myInt2 = br.ReadInt32();
      Console.WriteLine(myInt2);
      Int64 myInt64_r = br.ReadInt64();
      Console.WriteLine(myInt64_r);
      br.Close();
      fs.Close();
      Console.ReadLine();
    }
  }
}

Output:
test
a
12.345
42
123456789

Lower Level File Handling

This program shows low-level file handling at the byte level. It creates a file, saves the ASCII codes for "ABC", then reads and outputs the saved data.

using System;
using System.IO;

namespace filestream_cs
{
  static class Program
  {
    public static void Main(string[] args)
    {
      byte[] writeBytes = new byte[3]{65, 66, 67};         
      FileStream fs = null;
      try
      {
        // Create new file and open it for read and write. If the file exists, overwrite it.
        fs = new FileStream(@"test.txt", FileMode.Create);
        fs.Write(writeBytes, 0, 3); // Write 3 bytes from the start of the buffer.
      }
      finally
      {
        fs.Close();
      }

      byte[] readBytes = new byte[3];
      try
      {
        fs = new FileStream(@"test.txt", FileMode.Open, FileAccess.Read);
        fs.Read(readBytes, 0, 3);
      }
      finally
      {
        fs.Close();
      }
      foreach (byte readByte in readBytes)
      {
        char chr = System.Convert.ToChar(readByte);
        Console.Write(chr);
      }
      Console.ReadLine();     
    }
  }
}


Programming - a skill for life!

C# Demonstrations of I/O, arrays, methods, classes, loops, enums, pointers, file handling, Firebird databases, LINQ and drawing on a form