Programming Course in C# ¡Free!

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

Output



Solution


using System;
using System.IO;

class WritingFile
{
static void Main()
{
try
{
StreamWriter file = File.CreateText("test.dat");
string line;

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

if (line.Length != 0) 
{
file.WriteLine(line);
}
}
while(line.Length != 0);

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