2013-06-25 108 views
1

我有100个文本框,我试图让所有这些文本框将被写入一个文本文件的文本,这是我的代码:字符串writer写入文本文件

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开头。

+0

哪里是你的文件中定义在这里 – MDMalik

+0

很抱歉,但我不知道是什么意思ü你 – user2376998

+0

输出文件的路径没有定义 – MDMalik

回答

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

+0

嗨,感谢您的回复,文本文件仍然是空的。我不明白Streamwriter是如何工作的 – user2376998

2

这将是更好地为您使用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 + ","); 
0

尝试之前冲洗出来的流退出您的按钮点击事件使用:

stringWriter.Flush(); 
3

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

StringWriter.Close(); 

using (StringWriter stringwriter=new StringWriter()) 
{ 

//here is your code.... 
}