字符串作家写入文本文件

时间:2013-06-25 06:29:15

标签: c# text-files stringwriter

我有100个文本框,我试图将这些文本框中的所有文本写入文本文件,这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i <= 9; i++)
    {
        for (int j = 0; j <= 9; j++)
        {
            TextBox tb = new TextBox();
            tb.MaxLength = (1);
            tb.Width = Unit.Pixel(40);
            tb.Height = Unit.Pixel(40);
            // giving each textbox a different id  00-99
            tb.ID = i.ToString() + j.ToString();  
            Panel1.Controls.Add(tb);                       
        }
        Literal lc = new Literal();
        lc.Text = "<br />";
        Panel1.Controls.Add(lc);
    }
}

protected void btnShow_Click(object sender, EventArgs e)
{
    StringWriter stringWriter = new StringWriter();
    foreach (Control control in Panel1.Controls)
    {
        var textBox = control as TextBox;   
        if (textBox != null)
        {
            if (string.IsNullOrEmpty(textBox.Text))
            {                
                textBox.Style["visibility"] = "hidden";
            }
            // Write text to textfile.
            stringWriter.Write("test.txt", textBox.Text+","); 
        }  // end of if loop              
    }
}

我在dev文件夹中创建了一个文件名test.txt(我猜它在哪里)它没有任何错误,但文本文件中没有任何文本。这是正确的方法吗?因为当我尝试调试时,stringWriter的值将在第一个循环中以test.txt开头,在第二个循环中以test.txttest.txt开头。

4 个答案:

答案 0 :(得分:3)

使用StreamWriter类会更好:

StreamWriter sw = new StreamWriter("test.txt");  // You should include System.IO;

var textBox = control as TextBox;   
if (textBox != null)
{
   if (string.IsNullOrEmpty(textBox.Text))
   {
     textBox.Style["visibility"] = "hidden";
   }
}
sw.Write(textBox.Text + ","); 

答案 1 :(得分:3)

当您打开 StringWriter 时,数据不会保存到文件中。 在 btnShow_Click 结束时关闭它:

StringWriter.Close();

using (StringWriter stringwriter=new StringWriter())
{

//here is your code....
}

答案 2 :(得分:0)

问题出在提交代码

 protected void btnShow_Click(object sender, EventArgs e)
{
        System.IO.StreamWriter stringWriter= new System.IO.StreamWriter("c:\\test.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+","); // Write text to textfile. 

        }  // end of if loop              
    }

参考MSDNMSDN

答案 3 :(得分:0)

尝试在退出按钮点击事件之前使用以下内容清除流:

stringWriter.Flush();