I need help on why the text won't save to the file after first time.
Text won't save to the file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project_OSO
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Name Database \r");
Console.WriteLine("------------------------\n");
Console.WriteLine("What is your name?");
var name = Console.ReadLine();
var currentDate = DateTime.Now;
Console.WriteLine($"{Environment.NewLine}Hello, {name}, on {currentDate:d} at {currentDate:t}! Welcome to Name Database");
//File and path you want to create and write to
string fileName = @"C:\Users\Bruger\Desktop\NameDataBase";
//Check if the file exists
if (!File.Exists(fileName))
{
//Create the file and use streamWriter to write text to it.
//If the file existence is not check, this will overwrite said file.
//Use the using block so the file can close and variable disposed correctly
I have tried to find a way to get file to save, right now it saving the first time on a new file but when there is text in the file it won't save the new text.
using (StreamWriter writer = File.CreateText(fileName))
{
writer.WriteLine($"{Environment.NewLine} { name} on the date {currentDate:d} at {currentDate:t}");
}
}
Console.WriteLine("------------------------\r");
Console.WriteLine(" Name Database \n");
Console.Write($"{Environment.NewLine}Press to exit");
Console.ReadKey(true);
}
}
}
CodePudding user response:
You specifically have a check that skips the file saving if a file already exists.
I would assume you want to append to the file if it already exists.