Reputation: 25
I'm designing a program to save food recipes. The problem is when I save the ingredients of a new recipe it deletes the ingredients of the old recipe. I want both of them to be saved. Here's the code I use:
Console.WriteLine("Enter the path where your files will be saved: ");
string fileName = Console.ReadLine();
Console.WriteLine("Please enter the main ingrediant for your recipe: ");
string Main = Console.ReadLine();
Console.WriteLine("Please enter how many ingrediants in your recipe: ");
int Ingrediants = Convert.ToInt32(Console.ReadLine());
string[] a = new string[Ingrediants];
Recpies recipe1 = new Recpies(Main, Ingrediants);
recipe1.Ingrediants = new List<string[]>();
recipe1.TheMainIngrediant = Main;
Console.WriteLine("Please enter your ingrediants: ");
for (int i = 0; i < Ingrediants; i++)
{
a[i] = Console.ReadLine();
}
using (var file = System.IO.File.OpenText(fileName))
{
string line;
while ((line = file.ReadLine()?.Trim()) != null)
{
// skip empty lines
if (line == string.Empty)
{
recipe1.Ingrediants.Add(a);
recipe1.Saving(fileName, Ingrediants, a);
}
else
{
continue;
}
}
}
Upvotes: 2
Views: 95
Reputation: 49
Just add true
as second parameter
TextWriter tsw = new StreamWriter(fileName, true);
Upvotes: 0
Reputation: 2117
One possible way to achieve what you want is to use a combination between StreamWriter
and File.AppendText
, this is not going to overwrite the text
you already save on that file instead of that is going to append the info at the end of the file (this example might be helpful: Append Text). Hope this helps! 👍
Upvotes: 2