Custom Search

Friday, November 28, 2008

Adding new line to a txt file in C# .Net

In this very short article I will show you the easiest way to add a new text line on a txt file using C# .NET.

I was researching on this matter very hard. First I started to read the entire file to the end and then add the new line. There is a small problem on doing this: it might work at compilation time but when you execute the application, you will see an error that says that two processes cannot run at the same time. Sound fair.
Then I started working with locks. There are a couple of locks, the lock when you read and the lock when you write. This is good stuff to talk later but not right now.

So what is the easiest solution to this matter, here it is:

public void AddNewLine(String text)
File.AppendAllText("C:\\Logs.txt", text + Environment.NewLine);

Yes, just like that.
And if you want to read the txt file, you could do something like this:

public String ReadAll() {

StreamReader sr = new StreamReader("C:\\Logs.txt");
String allText = sr.ReadToEnd();
return allText;