Programming Course in C# ¡Free!

Appending to a text file

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program to ask the user for several sentences (until they just press Enter) and store them in a text file named "sentences.txt". If the file exists, the new content must be appended to its end.

Output



Solution


using System;
using System.IO;

class AppendingTextFile
{
static void Main()
{
try
{
StreamWriter file = File.AppendText("data.dat");
string line;

do
{
Console.Write("Enter a sentence: ");
line = Console.ReadLine();

if (line != "")
file.WriteLine(line);                
}
while(line != "");

file.Close();
}
catch (Exception)
{
Console.WriteLine("Error!!!");  
}
}
}