0

I would like to continue writing to an existing text file in my StringBuilder instead of replacing it with a new file.

Reason: To have ongoing logging to file from the datatable and clear it during the process to prevent hoarding up a big amount of memory if the program runs for a long time.

Is it possible?

Below is my current code which replaces with a new text file.

try
{
    var result = new StringBuilder();
    result.Append("#|ID|V1Records|V2Records|");
    result.AppendLine();

    foreach (DataRow row in SuccessTranslation.Rows)
    {
        for (int i = 0; i < SuccessTranslation.Columns.Count; i++)
        {
            result.Append(row[i].ToString());
            result.Append(i == SuccessTranslation.Columns.Count - 1 ? "\n" : "|");
        }
        result.AppendLine();
    }

    StreamWriter objWriter = new StreamWriter("C:\\Temp\\RecordsConversion_Success_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt", false);
    objWriter.WriteLine(result.ToString());
    objWriter.Close();
}

catch (Exception ex)
{
    log.LogError(Method, ex.Message.ToString());
}
gymcode
  • 4,431
  • 15
  • 72
  • 128

1 Answers1

1

Change this line:

StreamWriter objWriter = 
    new StreamWriter(
        "C:\\Temp\\RecordsConversion_Success_" + 
        DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt",
    false);

to:

StreamWriter objWriter = 
    new StreamWriter(
        "C:\\Temp\\RecordsConversion_Success_" +
        DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt", 
    true);

which will append the text instead of replacing it.

Minijack
  • 726
  • 7
  • 23