Can any one tell why the previous data is still displayed while saving data using StreamWriter

I am saving data to a file-name using Stream writer but if i run the code for second time the same data is appended to the previous data but i would like to clear the old data and write the data

The data i should have in text file should be as follows

101 435435345 3445454541104021031A094101                                                      
52251               1                   1         CCD1         110402110402   1111000020000001
6281110000251                00000000011              1                     1 0111000020000001
822500000100111000020000000000010000000000001                                  111000020000001
 9000001000001000000010011100002000000000001000000000000

My sample code

if (i == 0)
{
  index++;
  string m_strDate = DateTime.Now.ToString("yyyy/MM/dd");
  m_strDate = m_strDate.Replace("/", "");
  StrFilePath = "log" + m_strDate + index + ".txt";
}
  using (StreamWriter sw = new StreamWriter(StrFilePath,true))
    {
     using (StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.ASCII.GetBytes(strLine))))
    {
        while (sr.Peek() >= 0)
         {
           strReadLine = sr.ReadLine();
          if (strReadLine.StartsWith("1"))
           {
                if (i == 0)
              {
                  strFileHeader = strReadLine;
                  sw.WriteLine(strFileHeader);
               }
          }
   if (strReadLine.StartsWith("5"))
     {
     strBatchHeader = strReadLine;
      if (i == 0)
    {
         Btchno = Convert.ToInt32(strBatchHeader.Substring(87, 7));
        BatchCnt = Convert.ToInt16(Btchno);
       }
     if (i > 0)
    {
           BatchCnt++;
           strBatchHeader = strBatchHeader.Substring(0, 87) + Convert.ToString(BatchCnt.ToString().PadLeft(7, (char)48));
      }
    sw.WriteLine(strBatchHeader);
  }
   }
 }
 }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re passing true as the append parameter in the StringWriter constructor.

Method 2

Second parameter here: new StreamWriter(StrFilePath,true) is set to true, which means append to file. Set that parameter to false and it will work.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x