Csharp_learner
Csharp_learner

Reputation: 341

Append in a text file in C#

I am trying to write a txt file from C# as follows:

 File.WriteAllText("important.txt", Convert.ToString(c));
 File.WriteAllLines("important.txt", (from r in rec
                     select r.name + "   " + r.num1 + "   " + r.num2 + "   " + r.mult + "   " + r.rel).ToArray());

But the second File.WriteAllLines overrides the first entry in the file. Any suggestion how can I append data?

Upvotes: 2

Views: 17760

Answers (2)

Aleksandar Vucetic
Aleksandar Vucetic

Reputation: 14953

You should use File.AppendAllLines, so something like:

File.WriteAllText("important.txt", Convert.ToString(c));
File.AppendAllLines("important.txt", (from r in rec
                     select r.name + "   " + r.num1 + "   " + r.num2 + "   " + r.mult + "   " + r.rel).ToArray());

System.IO.File.AppendAllLines exists from .NET framework 4.0. If you are using .NET framework 3.5, there is AppenAllText method, and you can write your code like this:

File.WriteAllText("important.txt", Convert.ToString(c));
File.AppendAllText("important.txt", string.Join(Environment.NewLine, (from r in rec
                         select r.name + "   " + r.num1 + "   " + r.num2 + "   " + r.mult + "   " + r.rel).ToArray()));

Upvotes: 8

NoWar
NoWar

Reputation: 37633

Try this

 File.WriteAllLines("important.txt",  Convert.ToString(c) + (from r in rec
                     select r.name + "   " + r.num1 + "   " + r.num2 + "   " + r.mult + "   " + r.rel).ToArray());

Upvotes: 0

Related Questions