0

这是我的代码:

   protected void btnShow_Click(object sender, EventArgs e)
   {
      System.IO.StreamWriter stringWriter = new System.IO.StreamWriter(Server.MapPath(@"~/Puzzle/puzzle.txt"));
      foreach (Control control in Panel1.Controls)
      {
          var textBox = control as TextBox;   
          if (textBox != null)
          {
             if (string.IsNullOrEmpty(textBox.Text))
             {
                textBox.Style["visibility"] = "hidden";
             }
             stringWriter.Write(textBox.Text+",");
           }  // end of if loop              
      }
      stringWriter.Close();        
   }// end of button         

例如,我的文本文件如下所示:

,S,U,P,,,,,,,,

我希望它在我的文本文件中是这样的:

,S,U,P,
,,,,
,,,,

我希望它在击中第 4 个逗号后进入下一行。
我该怎么做?

4

1 回答 1

4

我希望它在击中第 4 个逗号后进入下一行。我该怎么做?

您可以跟踪到目前为止已写入的逗号数,一旦计数器达到 4,只需将其重置为 0 并在文件中添加一个新行:

protected void btnShow_Click(object sender, EventArgs e)
{
    using (var writer = new StreamWriter(Server.MapPath(@"~/Puzzle/puzzle.txt")))
    {
        int recordsWritten = 0;
        foreach (Control control in Panel1.Controls)
        {
            var textBox = control as TextBox;   
            if (textBox != null)
            {
                if (string.IsNullOrEmpty(textBox.Text))
                {
                    textBox.Style["visibility"] = "hidden";
                }
                stringWriter.Write(textBox.Text + ",");

                recordsWritten++;
                if (recordsWritten == 4)
                {
                    stringWriter.WriteLine();
                    recordsWritten = 0;
                }
            }
        }
    }
}
于 2013-06-25T07:09:41.610 回答