Write then read a text file

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet writes a text file from an internal string then reads it back using StreamReader, StreamWriter, TextReader, and TextWriter.

using System;
using System.IO;
 
public class WriteReadClass
{
   public static void Main()
   {
      // write a text file
      TextWriter tws = new StreamWriter ("test.txt");
    
      // write the current datetime to the stream
      tws.WriteLine (DateTime.Now);
    
      // write test strings to the stream
      tws.Write (" Test string 1 to write to file.\n");
      tws.Write (" Test string 2 to write to file.\n");
    
      tws.Close();   // close the stream
 
      // now, read in the text file
      TextReader trs = new StreamReader ("test.txt");
    
      // read the first line of text 
      Console.WriteLine (trs.ReadLine());
 
      // read the rest of the text lines
      Console.WriteLine (trs.ReadToEnd());
    
      trs.Close();   // close the stream
 
      Console.Write ("\nPress \"Enter\" to exit ...");
      Console.Read();
   }
}


 Write then read a text file (program output)
1/8/2008 2:02:26 PM

Test string 1 to write to file. Test string 2 to write to file.


Press "Enter" to exit ...





Personal tools