-1

I have a console application which writes details of the processed jobs into .txt file. I use this code to do it:

StreamWriter jp = new StreamWriter(jobsProcessed);
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
jp.Close();

Unfortunately every time a job is being processed new "info" string replaces the previous one. Is there any method to add new text to the end or beginning of the text file?

Bartosz
  • 4,542
  • 11
  • 43
  • 69

5 Answers5

2
StreamWriter jp = new StreamWriter(jobsProcessed,true);

Second parameter

//Determines whether data is to be appended to the file. If the file exists
//and append is false, the file is overwritten. If the file exists and append
// is true, the data is appended to the file. Otherwise, a new file is created.

http://www.dotnetperls.com/streamwriter http://social.msdn.microsoft.com/Forums/zh/clr/thread/17cd8ccf-7e53-41de-b4cc-221da70405a4

andy
  • 5,979
  • 2
  • 27
  • 49
2

You can use StreamWriter Constructor (String, Boolean), where second boolean parameter indicates either the data has to be appended to the already available one or not.

And also avoid calling Close and use using statement

using(StreamWriter jp = new StreamWriter(jobsProcessed))
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
   //jp.Close(); //NO NEED MORE
}

The good about this that even if exception occures, which can happen, the stream will be Disposed, by the way.

Tigran
  • 61,654
  • 8
  • 86
  • 123
2

There is an overload to the StreamWriter constructor which takes a second parameter called append;

using (StreamWriter jp = new StreamWriter(jobsProcessed, true))
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
}

It's also better practice to wrap your StreamWriter up in a using block like above.

Chris McAtackney
  • 5,192
  • 8
  • 45
  • 69
1

Just amend this:

StreamWriter jp = new StreamWriter(jobsProcessed);

To this:

StreamWriter jp = new StreamWriter(jobsProcessed, true);
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
0
// using (StreamWriter jp = new StreamWriter(jobsProcessed)) Overwrites, not good for you!
using (StreamWriter jp = new StreamWriter(jobsProcessed, true)) // Appends, good for you!
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
}

But you could semplify your code like so:

String[] content = File.ReadAllLines(jobsProcessed);

String[] newContent = new String[3];
newContent[0] = DateTime.Now.ToString();
newContent[1] = info;  
newContent[2] = "------";

File.AppendAllLines(jobsProcessed, newContent);
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98