Writing to a text file Learn programming C# Sharp

Lesson:

File Management


Exercise:

Writing to a text file 22


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"


Code:

using System;
using System.IO;
namespace FileWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            string sentence = " ";
            StreamWriter myfile;
            myfile = File.CreateText("test.txt");
            do
            {
                Console.Write("Enter a sentence: ");
                sentence = Console.ReadLine();
                if (sentence.Length != 0)
                {
                    myfile.WriteLine(sentence);
                }
            }
            while (sentence.Length != 0);
            myfile.Close();
        }
    }
}