Appending to a text file Learn programming C#



Lesson:

File Management


Exercise:

Appending to a text file


Objetive:

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.


Code:

using System;
using System.IO;
class Sentences
{
    static void Main(string[] args)
    {
        StreamWriter myFile = File.AppendText("file.txt");
        string line;

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

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

        myFile.Close();
    }
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.