Writing to a text file Learn programming C#

Lesson:

File Management


Exercise:

Writing 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"


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();
        }
    }
}

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