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();
}
}
Search
Write then read a text file
This C# code snippet writes a text file from an internal string then reads it back using StreamReader, StreamWriter, TextReader, and TextWriter.