0

我正在使用 Stream writer 将数据保存到文件名,但如果我第二次运行代码,相同的数据会附加到以前的数据中,但我想清除旧数据并写入数据

我应该在文本文件中的数据应该如下

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

我的示例代码

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);
  }
   }
 }
 }
4

2 回答 2

6

您在构造函数中true作为append参数传递。StringWriter

于 2011-04-07T13:33:16.627 回答
1

这里的第二个参数:new StreamWriter(StrFilePath,true)设置为true,表示追加到文件。将该参数设置为false,它将起作用。

于 2011-04-07T13:33:32.313 回答