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.
Example Code
// Importing necessary namespaces to handle input/output functionalities
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Informing the user about the functionality of the program
Console.WriteLine("Enter sentences (press Enter on an empty line to finish):");
// Initializing a StreamWriter to append data to "sentences.txt" without overwriting
using (StreamWriter writer = new StreamWriter("sentences.txt", append: true))
{
// Infinite loop to continuously gather sentences from the user
while (true)
{
// Reading a sentence from the user's input
string sentence = Console.ReadLine();
// Checking if the input is empty to end the input gathering process
if (string.IsNullOrEmpty(sentence))
break; // Exiting the loop if no sentence is entered
// Writing the user's sentence to the file, appending it to the end
writer.WriteLine(sentence);
}
}
// Informing the user that the sentences have been appended to the file
Console.WriteLine("Sentences appended to sentences.txt.");
}
}