Write text to text file - CSharp File IO

CSharp examples for File IO:Text File

Description

Write text to text file

Demo Code

using System;//from ww w . ja v  a  2  s. c  o  m
using System.IO;
class TextReaderWriter
{
   public static void WriteTextToFile()
   {
      string textLine;
      StreamWriter outStream = null;
      try
      {
         FileInfo textFile = new FileInfo(@"C:\MyTestFiles\MyStory.txt");
         outStream = textFile.CreateText();
         Console.WriteLine("Writing to text file");
         Console.WriteLine("Please write three lines of text\n");
         for (int i = 0; i < 3; i++)
         {
            textLine = Console.ReadLine();
            outStream.WriteLine(textLine);
         }
      }
      catch (IOException exObj)
      {
         Console.WriteLine(exObj);
      }
      finally
      {
         outStream.Close();
      }
   }
   public static void ReadTextFromFile()
   {
      string textLine;
      StreamReader inStream = null;
      try
      {
         FileInfo textFile = new FileInfo(@"C:\MyTestFiles\MyStory.txt");
         inStream = textFile.OpenText();
         Console.WriteLine("\nReading from text file: \n");
         textLine = inStream.ReadLine();
         while (textLine != null)
         {
            Console.WriteLine(textLine);
            textLine = inStream.ReadLine();
         }
      }
      catch (IOException exObj)
      {
         Console.WriteLine(exObj);
      }
      finally
      {
         inStream.Close();
      }
   }
}
class Tester
{
   public static void Main()
   {
      TextReaderWriter.WriteTextToFile();
      TextReaderWriter.ReadTextFromFile();
   }
}

Result


Related Tutorials